wp/wordpress文章摘要提取
七娃博客664人阅读
之前开发主题调取摘要部分的时候,总是按照下面的方式直接输出文章里面前200个字的内容:
<?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 200,''); ?>
能用是能用,就是不美观,因为这个方法不能过滤代码、空格以及特殊符号,今天研究别人主题,发现了它的方法,就提取出来了,很好用!
1.functions.php添加以下代码:
function get_abstract($content = '',$size = 130){ if(!$content){ global $post; $excerpt = $post->post_excerpt; $content = $excerpt ? $excerpt : $post->post_content; } return mb_strimwidth(clear_code(strip_tags(strip_shortcodes($content))), 0, $size,'...'); } /* * 清除字符串中的标签 */ function clear_code($string){ $string = trim($string); if(!$string) return ''; $string = preg_replace('/[#][1-9]\d*/','',$string);//清除图片索引(#n) $string = str_replace("\r\n",' ',$string);//清除换行符 $string = str_replace("\n",' ',$string);//清除换行符 $string = str_replace("\t",' ',$string);//清除制表符 $pattern = array("/> *([^ ]*) *</","/[\s]+/","/<!--[^!]*-->/","/\" /","/ \"/","'/\*[^*]*\*/'","/\[(.*)\]/"); $replace = array(">\\1<"," ","","\"","\"","",""); return preg_replace($pattern,$replace,$string); }
2.调用摘要
<?php echo get_abstract(); ?>
效果:
评论 | 0 条评论
登录之后才可留言,前往登录