如何在WordPress中判断当前页面是否为博客文章?
解决方案
在WordPress主题开发中,你可以通过核心条件判断函数精准区分博客文章和普通页面:
is_single():专门判断当前是否为单篇博客文章(post类型)页面is_page():判断当前是否为普通页面(page类型)is_front_page():判断当前是否为网站首页
你当前的代码逻辑存在严谨性问题:is_singular()会匹配所有单条内容页面(包括page和post),虽然因为前置的is_page()判断,实际走到该分支的只有博客文章,但直接用is_single()会让代码逻辑更清晰直观。
修改后的代码如下:
<?php get_header(); ?> <?php if (is_front_page()) : ?> <div class="hero"> <h1>hello world</h1> </div> <?php elseif (is_page()) : ?> <div class="hero"> <h1><?php the_title(); ?></h1> </div> <?php elseif (is_single()) : ?> <div class="hero"> <h1><?php the_title(); ?></h1> <p>Date: <?php echo get_the_date(); ?></p> <p>Categories: <?php the_category(', '); ?></p> </div> <?php endif; ?> <?php get_footer(); ?>
额外说明:
- 若需判断自定义文章类型,可使用
is_singular('custom_post_type'),将custom_post_type替换为你的自定义文章类型标识 - 代码中补全了分类显示逻辑
<?php the_category(', '); ?>,可直接输出文章所属分类,分类间用逗号分隔
内容的提问来源于stack exchange,提问作者Marcus
相关产品推荐
相关产品推荐

