WordPress 自定义循环里取不到分类,the_post 忘调了

· wordpress · 阅读 15
摘要

照手册写了个 WP_Query,正文标题能出来,get_the_category() 返回空数组。不报错,就是不显示。查了一个多小时。have_posts() 只挪游标,the_post() 才塞全局我总是把这俩当成一回事。实际上 the_

照手册写了个 WP_Query,正文标题能出来,get_the_category() 返回空数组。不报错,就是不显示。查了一个多小时。

have_posts() 只挪游标,the_post() 才塞全局

我总是把这俩当成一回事。实际上 the_post() 干两件事:把当前文章写进全局 $post,再触发 setup_postdata。少了它,模板标签读的还是页面上一条,或者 ID=0,分类自然查不到。

<?php
$q = new WP_Query( array( 'posts_per_page' => 5 ) );
if ( $q->have_posts() ) :
    while ( $q->have_posts() ) : $q->the_post(); ?>
        <h3><?php the_title(); ?></h3>
        <?php the_category( ', ' ); ?>
    <?php endwhile;
endif;
wp_reset_postdata();

文件是 index.php 或任意模板,位置看你要放在哪块。

循环后面那句 reset 别省

wp_reset_postdata() 不调,主循环的全局 $post 被你顶掉了,页面底部一堆东西会错乱——面包屑、相关文章、分页。我踩过一次,症状是页脚的时间变成最后一篇的。当时完全没想到是这儿。

如果循环里要靠全局状态的东西不多,还有个捷径:get_posts() 返回数组,配 setup_postdata 手动 setup。我一般懒得这么写,容易漏。