I’m trying to create a related posts WP_Query. So far, I’ve to created a custom WP_Query that queries all posts that match an array of tags.

However, I’m trying to create a simple if statement: if the number of posts fetched are less than 10, get the remainder from elsewhere (this could be from a particular category).

I have the following loop. It uses $related_posts->found_posts to get the number of posts.

$related_posts_args =
    array(
    'tag__and' => $list_of_tags, // array of tag IDS
    'posts_per_page' => 10,
    'post__not_in' => $already_posted, // array of post IDs
    'post_type' => 'post',
    'post_status' => 'publish',
    'orderby' => 'date',
    'order' => 'DESC',
    'orderby' => 'rand',
);

$related_posts_query = new WP_Query( $related_posts_args );
if ( $related_posts_query->have_posts() ):
    while ( $related_posts_query->have_posts() ):
        $related_posts_query->the_post();
// this is the number of posts in my current query
    echo $related_posts_query->found_posts; 
            the_title();
    endwhile;
endif;
wp_reset_postdata();

Would anyone know how use the remainder to get posts from elsewhere? (And is possible within the same loop).

2 s
2

You could do something like :

$related_posts_query = new WP_Query( $related_posts_args );
if( $related_posts_query->found_posts < 10 ){
   $args = array(/* new wp_query args*/);
   $newquery = new WP_Query( $args );
}

# merge the two results
$related_posts_query->posts = array_merge( $related_posts_query->posts, $newquery->posts );
$related_posts_query->post_count = count( $related_posts_query->posts );

# do your loop here

Leave a Reply

Your email address will not be published. Required fields are marked *