A-
A+
WordPress文章用PHP截取摘要的两种做法:按字符个数截取 和 按视觉宽度截取
最近遇到了这个坑,发现文章摘要每一篇截取的文字宽度都不同,仔细研究了一番发现使用了按字符个数截取的方法,今天在此记录一下。
直接上代码:
用字符个数截取(后果就是每篇文章截取的文字数量不一样,尤其是中文英文混合的)
$excerpt_text = im2828_excerpt_cache_get(get_the_ID());
//兜底:无缓存时现场裁切,不写入数据库
if($excerpt_text === false){
$post = get_post();
$raw = strip_tags($post->post_content);
if($post->post_type === 'bulletin'){
$excerpt_text = mb_substr($raw,0,65);
}else{
$excerpt_text = mb_substr($raw,0,290);
}
}
按视觉宽度截取(推荐)
function template_get_cached_excerpt_memory($post_id){
global $post;
$arr = $GLOBALS['_cached_post_excerpt'] ?? [];
if(isset($arr[$post_id]) && !empty($arr[$post_id]->short_290)){
return $arr[$post_id]->short_290;
}
if( ! $post || $post->ID !== $post_id ){
return '';
}
if(!empty($post->post_excerpt)){
$raw = $post->post_excerpt;
}else{
$raw = wp_strip_all_tags($post->post_content, true);
}
return mb_strimwidth(trim($raw),0,290,'...');
}
