wordpress如何正确自动获取中文日志摘要

WordPress 函数 get_the_excerpt() 可以获取日志的摘要,如果没有摘要,它会自动获取内容,并且截取。但是由于无法正确统计中文字符数,我爱水煮鱼撰写了下面这个函数来解决这个问题。

function get_post_excerpt($post, $excerpt_length=240){
    if(!$post) $post = get_post();

    $post_excerpt = $post->post_excerpt;
    if($post_excerpt == ''){
        $post_content = $post->post_content;
        $post_content = do_shortcode($post_content);
        $post_content = wp_strip_all_tags( $post_content );

        $post_excerpt = mb_strimwidth($post_content,0,$excerpt_length,'…','utf-8');
    }

    $post_excerpt = wp_strip_all_tags( $post_excerpt );
    $post_excerpt = trim( preg_replace( "/[

	 ]+/", ' ', $post_excerpt ), ' ' );

    return $post_excerpt;
}

将上面的代码复制到当前主题的 functions.php

调用:在single.php插入如下代码

<p><?php echo get_post_excerpt(); ?></p>
原文地址:https://www.cnblogs.com/ytkah/p/3410762.html