·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设问答 >> 让WordPress的摘要显示自定义排版格式

让WordPress的摘要显示自定义排版格式

作者:佚名      网站建设问答编辑:admin      更新时间:2022-07-23

WordPress默认的Excerpt(摘要)排版格式有些不尽人意,首先它默认的摘要输出字数是55,不支持HTML标签,也就是输出的内容不会换行,都是一大长段;此外JavaScript也无法被剥离出来。严重影响版面的美观性,除非是手动录入摘要内容。

我们要做的就是让自动提取的Excerpt(摘要)内容(非手动输入),显示自定义的排版格式。实现方法如下:

WordPress默认摘录的功能是在wp-includes/formatting.php这个文件里,我们要修改的只有主题functions.php文件,请把下面的代码加入到functions.php文件中

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'improved_trim_excerpt');
function improved_trim_excerpt($text) {
        global $post;
        if ( '' == $text ) {
                $text = get_the_content('');
                $text = apply_filters('the_content', $text);
                $text = str_replace('\]\]\>', ']]>', $text);
                $text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text);
                $text = strip_tags($text, '<p>');
                $excerpt_length = 80;
                $words = explode(' ', $text, $excerpt_length + 1);
                if (count($words)> $excerpt_length) {
                        array_pop($words);
                        array_push($words, '[...]');
                        $text = implode(' ', $words);
                }
        }
        return $text;
}

这段代码中是将wp-includes/formatting.php里的

wp_trim_excerpt()

改为了

improved_trim_excerpt()

修改摘要内容输出的字数

$excerpt_length = 80;

让摘要内容支持HTML标签

$text = strip_tags($text, '<p>');

如果想加入更多的HTML标签,请在“<p>”的后面紧随着加入。

删除不需要的JavaScript代码

$text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text);