WordPress教程

判断 WordPress 文章内容是否为空

阿里云

如想在 WordPress 文章正文内容为空时,显示或隐藏某些内容,可以用下面的判断代码。其中比较有用的是文章中无图片时,在文章列表显示不同的样式。

方法一

  1.     <?php $content = get_post()->post_content;
  2.     if( empty( $content ) ) { ?>
  3.     无内容
  4.     <?php } else { ?>
  5.     有内容
  6.     <?php } ?>
也想出现在这里?联系我们
创客主机

方法二

  1.     <?php if ($post->post_content == '') { ?>
  2.     无内容
  3.     <?php } else { ?>
  4.     有内容
  5.     <?php } ?>

方法三

  1.     <?php if ( get_the_content() ) { ?>
  2.     有内容
  3.     <?php } else { ?>
  4.     无内容
  5.     <?php } ?>

方法四

添加自定义函数

  1.     function empty_content($str) {
  2.         return trim(str_replace('&nbsp;','',strip_tags($str))) == '';
  3.     }

使用方法:

  1.     <?php if ( empty_content( $post->post_content ) ) { ?>
  2.     无内容
  3.     <?php } else { ?>
  4.     有内容
  5.     <?php } ?>

以此类推,可以判断文章中是否有图片:

  1.     function empty_img_content($str) {
  2.     	return trim(str_replace('&nbsp;','',strip_tags($str,'<img>'))) == '';
  3.     }

使用方法:

  1.    <?php if ( empty_img_content( $post->post_content ) ) { ?>
  2.     无图
  3.     <?php } else { ?>
  4.     有图
  5.     <?php } ?>

补一个:文章列表不显示无内容文章

  1.     function my_filter_where( $where = '' ) {
  2.     	return $where .= "AND trim(coalesce(post_content, '')) <>''";
  3.     }
  4.     add_filter( 'posts_where', 'my_filter_where' );

判断 WordPress 文章内容是否为空

已有 171 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!