自定义摘录长度

时间:2021-07-23 03:23:20

标签: php wordpress

add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
/**
* Change the length of excerpt.
*
* @param int $length The number of words. Default 55.
* @return int New excerpt length.
*/
function custom_excerpt_length( $length ) {

    return 20; // number of words. Default is 55.
}

此函数返回我博客文章摘录中的 20 个单词。我如何自定义它而不是 20 个字,而是返回我帖子的第一段。

1 个答案:

答案 0 :(得分:0)

在functions.php文件中添加如下函数,返回post的第一段

add_filter( 'wp_trim_excerpt', 'erginous_custom_excerpt', 10, 2 );

function erginous_custom_excerpt($text, $raw_excerpt) {
    if( ! $raw_excerpt ) {
        $content = apply_filters( 'the_content', get_the_content() );
        $text = substr( $content, 0, strpos( $content, '</p>' ) + 4 );
    }
    return $text;
}

该函数添加了一个过滤器,通过检查手动摘录来修改 wp_trim_excerpt 返回值。