如想在 WordPress 文章正文内容为空时,显示或隐藏某些内容,可以用下面的判断代码。其中比较有用的是文章中无图片时,在文章列表显示不同的样式。文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
方法一文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
<?php $content = get_post()->post_content; if( empty( $content ) ) { ?> 无内容 <?php } else { ?> 有内容 <?php } ?>
方法二文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
<?php if ($post->post_content == '') { ?> 无内容 <?php } else { ?> 有内容 <?php } ?>
方法三文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
<?php if ( get_the_content() ) { ?> 有内容 <?php } else { ?> 无内容 <?php } ?>
方法四文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
添加自定义函数文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
function empty_content($str) { return trim(str_replace(' ','',strip_tags($str))) == ''; }
使用方法:文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
<?php if ( empty_content( $post->post_content ) ) { ?> 无内容 <?php } else { ?> 有内容 <?php } ?>
以此类推,可以判断文章中是否有图片:文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
function empty_img_content($str) { return trim(str_replace(' ','',strip_tags($str,'<img>'))) == ''; }
使用方法:文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
<?php if ( empty_img_content( $post->post_content ) ) { ?> 无图 <?php } else { ?> 有图 <?php } ?>
补一个:文章列表不显示无内容文章文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html
function my_filter_where( $where = '' ) { return $where .= "AND trim(coalesce(post_content, '')) <>''"; } add_filter( 'posts_where', 'my_filter_where' );文章源自知更鸟-https://zmingcx.com/check-if-wordpress-post-content-is-empty.html

评论