Repeatting wordpress posts inside one single loop untill it reachers a certain number of posts

Take a look at this awesome code from John P Bloch. What this code does is:

It looks to see how many posts are going to be displayed by default. If it’s fewer than 20, it grabs the difference (in this case, it should grab 10 posts) and appends them to the current query. Then it recurses through itself to see if it’s still under 20 posts. If so, it continues to run until it hits at least 20 posts.

Read More
function my_awesome_post_booster(){
      if(!is_home())
        return;
      global $wp_query;
      if( $wp_query->post_count < 20 ){
        $how_many = 20 - $wp_query->post_count;
        $newposts = get_posts('numberposts='.$how_many);
        $wp_query->posts = array_merge( $wp_query->posts, $newposts );
        $wp_query->post_count += count($newposts);
        my_awesome_post_booster();
      }
    }

    add_action('template_redirect', 'my_awesome_post_booster');

Problem is, it does not recurses throught itself, it does not continue.

Lets say i have 5 posts, the code should repeat them 4 times until it reaches 20. But it doesn’t.

Any ideas why? Ty

P.S. here is my idea, tho not sure how to put it in php.

Lets say i have 5 posts.

$wp_query->post_count will be 5

$how_many = 20 - $wp_query->post_count; will be 15

$newposts = get_posts('numberposts='.$how_many); - will try to get 15 posts, but it can't, cause the blog only has 5!

The scrip thinks he pulled 15, even tho he didn't.

The idea is to divide $how_many to the actual number of posts which is 5, but get an even number…. Like this:

$how_many = 20 - $wp_query->post_count; will be 15
divide $how_many with $wp_query->post_count;
make sure it's an even number, lets say 3,33, makes it 3... 
 $newposts = get_posts('numberposts='.$that_numer);

What do u think? 🙂 Can i put this into php?

Related posts

Leave a Reply

1 comment

  1. The function is calling itself over and over but has no default return! This may not be causing your issues here, but it will certainly cause memory leaks if its used too much! I would consider adding a return true to the very bottom of the function otherwise each instance will remain in memory, when it shouldn’t