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).
You could do something like :
The best approach IMO is to count the posts returned per page against the set
posts_per_page
option set in your query. If the count is less than the setposts_per_page
, calculate the difference and then use this as the amount of posts to fill the rest in a custom queryThis is how it should work:
First, count the amount of posts returned by your “main” query, in this situation, this will be
$related_posts_args->posts
As you have set your
posts_per_page
to10
, this will be the number to check the count against.If the count is less than 10, you need to get the difference between 10 and the count. This difference will be the
posts_per_page
option for your custom queryYou can now run your custom query to retrieve the posts to fill the blank spaces. You will just need to add your own query arguments
Here is the complete code
With your code integrated