在WordPress循环中,我想有条件地检查帖子是否有标题,以便提供必要的包装HTML。如果文章没有标题,我不希望出现任何包装HTML。
有没有办法有条件地检查WordPress帖子的标题是否为空?
4 个回复
最合适的回答,由SO网友:Howdy_McGee 整理而成
在循环过程中,您可以对照WP_Post Object 像这样:
<?php while( have_posts() ) : the_post(); ?>
<?php if( ! empty( $post->post_title ) ) : ?>
<h1><?php the_title(); ?></h1>
<?php endif; ?>
<?php endwhile; ?>
SO网友:Milo
检查时$post->post_title
, 正如Howdy\\u McGee的回答,在大多数情况下可能是安全的,在某些情况下,标题可能会被修改the_title
滤器在这种情况下,您必须通过API获取标题,以确定它是否真的为空。
$title = trim( get_the_title() );
if( ! empty( $title ) ){
echo \'there is a title\';
} else {
echo \'empty title\';
}
SO网友:Daren Zammit
您可以将前后html标记添加到the_title() 作用如果post\\u标题为空,则不会输出任何内容。
the_title(\'<h1>\', \'</h1>\');
SO网友:fwho
展开的步骤@Milo\'s答案。
echo $title = ( ! empty( trim( get_the_title())) ? "there is a title" : "empty title";
或echo $title = ( ! empty( trim( get_the_title())) ?: "empty title";
结束