在单个循环内重复wordpress帖子,直到达到一定数量的帖子

时间:2010-08-27 10:44:39

标签: php wordpress

看看John P Bloch的这个很棒的代码。这段代码的作用是:

它会查看默认显示的帖子数量。如果它少于20,它会抓住差异(在这种情况下,它应该抓住10个帖子)并将它们附加到当前查询。然后它通过自己递归来查看它是否仍然在20个帖子之下。如果是这样,它会继续运行直到它至少发布20个帖子。

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');

问题是,它本身不会递归,它不会继续。

假设我有5个帖子,代码应该重复4次,直到达到20.但它没有。

任何想法为什么? TY

P.S。这是我的想法,不知道如何把它放在PHP中。

假设我有5个帖子。

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

这个想法是将$ how_many除以实际的帖子数量为5,但得到一个偶数......就像这样:

$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);
你怎么想? :)我可以将它放入php吗?

1 个答案:

答案 0 :(得分:0)

该函数反复调用自身,但没有默认返回!这可能不会导致您的问题,但如果使用太多,肯定会导致内存泄漏!我会考虑在函数的最底部添加一个返回true,否则每个实例都将保留在内存中,当它不应该

相关问题