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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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( "/[\n\r\t ]+/", ' ', $post_excerpt ), ' ' );
 
    return $post_excerpt;
}

 

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

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

1
<p><?php echo get_post_excerpt(); ?></p>

 

posted @   ytkah  阅读(433)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
网址导航 gg N / G Sitemap

部分内容来源于网络,如有版权问题请联系删除

  
点击右上角即可分享
微信分享提示