How to show more random posts if Tag has less than 3 posts

There are two steps to get this working:

  1. Add a counter to your main loop, so you can check how many posts are output.

  2. If your counter is less than 3, run a second query and output.

So for step 1, set a counter before your loop and increment it each time the loop runs, like so:

<?php
// create your counter variable
$counter = 0;
if (have_posts()) :
    while (have_posts()) : the_post();
    // add 1 to your counter, as 1 post was just output
    $counter++;
    // (display the posts)
    endwhile;
endif; ?>

Step two: check your counter variable, then run another query if needed.

<?php
// if counter is less than 3, run a separate query
if($counter < 3) {
    // get the ID of the current Tag
    $tag_id = get_queried_object()->term_id;
    // set up query arguments
    $args = array(
        // only pull Posts
        'post_type' => 'post',
        // don't pull Posts that have the current Tag - prevents duplicates
        'tag__not_in' => array("$tag_id"),
        // set how many Posts to grab
        'posts_per_page' => 3
    );
    $extraPosts = new WP_Query($args);
    if($extraPosts->have_posts()):
        while($extraPosts->have_posts()) : $extraPosts->the_post();
        // display the posts)
        endwhile;
    endif;
} ?>

If you want the Tag Archive to always show exactly 3 posts, then right after the opening part of the “if” statement, calculate how many to get:

$numberToGet = 3 - $counter;

then set 'posts_per_page' => "$numberToGet" so it’s dynamic.