WP 优化

WordPress 截取摘要长度

2年前 (2021-10-20)   1.3k   658 字

the_excerpt()
输出当前文章的摘要,并会附上 “ […] ” ,这不是“更多”的链接。如果你没有提供一篇文章明确的摘要,它将自动摘录文章内容中前55个字作为摘要。而 HTML 标签和图片都会从摘要内容中去除。此标签必须用在主循环里。
用法

<?php the_excerpt(); ?>

这个函数没有参数,输出长度是固定的55字符。且默认截取的是55个英文单词,在中文中无法截取到55个汉字。

我们可以添加下边的代码到你的主题的 functions.php 里面

// 重新定义摘要的字数
function custom_excerpt_length( $length ){
    return 200;         // 200 就是文字个数,根据自己的需要设置
}
add_filter( 'excerpt_length', 'custom_excerpt_length');
// 重新定义结尾符号,改为文章的链接
function new_excerpt_more( $more ) {
    return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">Read More...</a>';
}
add_filter( 'excerpt_more', 'new_excerpt_more' );


// 重新定义结尾符号,不需要文章链的 
function new_excerpt_more( $more ) {
    return ' ...'; 
}
add_filter( 'excerpt_more', 'new_excerpt_more' );

根据自己的需要选择即可。

版权声明:Jakehu 发表于 2021-10-20 18:53:26
转载请注明:WordPress 截取摘要长度︱Jakehu

您可能感兴趣的

暂无评论

暂无评论...