为何 single.php 中也使用 loop have_posts

文章目录

    single.php 是用来展示单个博文的,但是会看到 wordpress 4.7.3 默认主题 twentyseven 的 single.php 代码中依然使用的是 loop 逻辑。一个文章为何还要使用 loop ?

    <div class="wrap">
    	<div id="primary" class="content-area">
    		<main id="main" class="site-main" role="main">
    
    			<?php
    				/* Start the Loop */
    				while ( have_posts() ) : the_post();
    
    					get_template_part( 'template-parts/post/content', get_post_format() );
    
    					if ( comments_open() || get_comments_number() ) :
    						comments_template();
    					endif;
    
    				endwhile; // End of the loop.
    			?>
    
    		</main><!-- #main -->
    	</div><!-- #primary -->
    	<?php get_sidebar(); ?>
    </div><!-- .wrap -->
    
    

    实际上,have_posts 即使不调用,只调用 the_post,single.php 对应的页面也能正常展示,因为 the_post 设置了全局变量 $post 即代表了 single post object。

    调用 have_posts 是为了与三方插件 100% 兼容,因为 loop_start / loop_end action 只有在首尾两次调用 have_posts() 的时候才会被触发。

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式