如想在 WordPress 文章正文内容为空时,显示或隐藏某些内容,可以用下面的判断代码。其中比较有用的是文章中无图片时,在文章列表显示不同的样式。
方法一
- <?php $content = get_post()->post_content;
- if( empty( $content ) ) { ?>
- 无内容
- <?php } else { ?>
- 有内容
- <?php } ?>
方法二
- <?php if ($post->post_content == '') { ?>
- 无内容
- <?php } else { ?>
- 有内容
- <?php } ?>
方法三
- <?php if ( get_the_content() ) { ?>
- 有内容
- <?php } else { ?>
- 无内容
- <?php } ?>
方法四
添加自定义函数
- function empty_content($str) {
- return trim(str_replace(' ','',strip_tags($str))) == '';
- }
使用方法:
- <?php if ( empty_content( $post->post_content ) ) { ?>
- 无内容
- <?php } else { ?>
- 有内容
- <?php } ?>
以此类推,可以判断文章中是否有图片:
- function empty_img_content($str) {
- return trim(str_replace(' ','',strip_tags($str,'<img>'))) == '';
- }
使用方法:
- <?php if ( empty_img_content( $post->post_content ) ) { ?>
- 无图
- <?php } else { ?>
- 有图
- <?php } ?>
补一个:文章列表不显示无内容文章
- function my_filter_where( $where = '' ) {
- return $where .= "AND trim(coalesce(post_content, '')) <>''";
- }
- add_filter( 'posts_where', 'my_filter_where' );
- 1、本站大部分内容均收集于网络,若内容侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn,我们将第一时间处理!
- 2、本站资源所需价格并非资源售卖价格,是收集、整理、编辑以及本站运营的适当补贴,并且本站不提供任何免费技术服务。
- 3、所有资源仅限参考和学习,版权归原作者所有,更多请阅读无言说网络服务器协议。