WordPress判断文章内容为空时显示不同的样式

2023-11-26 173 0

如想在 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('&nbsp;','',strip_tags($str))) == '';
    }

使用方法:

<?php if ( empty_content( $post->post_content ) ) { ?>
    无内容
    <?php } else { ?>
    有内容
    <?php } ?>

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

    function empty_img_content($str) {
    	return trim(str_replace('&nbsp;','',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' );

 

    相关文章

    wordpress制作一个简洁的tags聚合页面
    如何制作一个WordPress采集插件并将其添加到后台
    如何制作一个对接腾讯COS云存储的WordPress插件
    WordPress怎么获取TAG随机标签
    WordPress分类页面或文章页面获取当前分类ID
    WordPress主题开发:如何给文章添加卡片式内链及美化教程

    发布评论