为什么这个结果是空的?这是不对的。只有一个帖子

时间:2015-01-30 作者:TheWebs

我有一个类别,叫做事件。它被分配到一个职位。因此,我创建了以下循环:

$args = array (\'category_name\' => \'events\', \'posts_per_page\' => 4, \'orderby\' => \'date\', \'order\' => \'DESC\' );
$category_posts = new WP_Query($args);

if ($category_posts->have_posts()) {
  while ($category_posts->have_posts()) {
    $category_posts->the_post();
    var_dump($category_posts->the_post());

    ?>
      <div class="col-md-6">
        <?php $category_posts->the_post_thumbnail(array(\'class\' => \'events-image\')); ?>
      </div>
      <div class="col-md-6">
        <h4><?php echo $category_posts->the_title(); ?></h4>
        <span class="date"><?php echo date(\'M j, Y\', $category_posts->get_the_date()); ?></span>
        <p><?php echo implode(\' \', array_slice(str_word_count($category_posts->the_content(), 2), 0,120)); ?> [...]</p>
      </div>
    <?php
  }
}
请注意var_dump($category_posts->the_post()); 它来到这里并这样做var_dump 但输出是NULL. wtf?

令人困惑的是,它有帖子,它进入while语句,但$category_posts->the_post() 是否为空?这几乎毫无意义。

更新1修复了评论者建议的参数数组。是order_by, 更改为orderby

1 个回复
最合适的回答,由SO网友:Hybrid Web Dev 整理而成

As per wordpress codex, the_post() "Iterate the post index in The Loop. Retrieves the next post, sets up the post, sets the \'in the loop\' property to true." This all occurs within the post object itself.

If you only have 1 post, and run the_post twice, you\'ll reach the end of the post count. In this case, even doing a var_dump of the_post still runs the function, which is why you\'re not seeing results below...you\'ve already reached the end of the loop before you start trying to output data.

Also "This function does not return any values."

Meaning your var_dump will always return null, because you\'re dumping the results of a function which returns nothing.

If you want useful results, var_dump($category_posts) will return the post object, which will contain any posts found and other information. ->the_post is just a method of the post object itself.

结束

相关推荐

Custom taxonomy template loop

我知道这个问题问得很多,但我找不到一个适合我的答案。我制作了一些自定义帖子类型和一些自定义分类法。我有自定义的帖子类型Products 并与分类法相联系Product Categories. 当用户在产品页面上单击产品类别时,我想向他显示该特定类别中的所有产品。问题是,产品类别将约为50种。现在我发现的唯一一件事就是把这个<?php $loop = new WP_Query( array( \'post_type\' => \'all_products\', \'posts_per_page\