Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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).

share|improve this question

1 Answer 1

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.