钩子文档

excerpt_more

💡 云策文档标注

概述

excerpt_more 是一个 WordPress 过滤器,用于修改在摘要末尾显示的“更多”链接字符串。它由 wp_trim_excerpt() 函数调用,默认输出‘[…]’。

关键要点

  • 过滤器名称:excerpt_more,参数为 $more_string(字符串类型),表示“更多”链接中显示的文本。
  • 核心用途:允许开发者自定义摘要后的“更多”指示符,例如替换为其他文本或添加链接。
  • 关联函数:主要与 wp_trim_excerpt() 配合使用,用于生成和处理摘要内容。
  • 版本历史:自 WordPress 2.9.0 版本引入。

代码示例

// 示例1:将‘[…]’替换为‘…’
function my_theme_excerpt_more( $more ) {
    return '…';
}
add_filter( 'excerpt_more', 'my_theme_excerpt_more' );

// 示例2:添加带链接的“继续阅读”
function wpdocs_excerpt_more( $more ) {
    return sprintf( '<a href="%1$s">%2$s</a>',
        esc_url( get_permalink( get_the_ID() ) ),
        sprintf( __( 'Continue reading %s', 'wpdocs' ), '<span class="screen-reader-text">' . get_the_title( get_the_ID() ) . '</span>' )
    );
}
add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );

// 示例3:自定义字符串
function custom_excerpt_more( $more ) {
    return '[.....]';
}
add_filter( 'excerpt_more', 'custom_excerpt_more' );

注意事项

  • 在 WordPress 2.9 及以上版本使用 excerpt_more 过滤器;对于更早版本,可能需要使用 wp_trim_excerpt 过滤器进行替代处理。
  • 确保返回值为字符串类型,以正确显示在摘要末尾。
  • 建议在主题的 functions.php 文件中添加过滤器代码,以实现自定义效果。

📄 原文内容

Filters the string in the “more” link displayed after a trimmed excerpt.

Parameters

$more_stringstring
The string shown within the more link.

More Information

This filter is called by the wp_trim_excerpt() function. By default, the filter is set to echo ‘[…]’ as the excerpt more string at the end of the excerpt.

Source

$excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes

  1. Skip to note 6 content


    Anonymous User



    How To Add A “Continue Reading” Link To Excerpts

    function wpdocs_excerpt_more( $more ) {
        return sprintf( '<a href="%1$s" class="more-link">%2$s</a>',
              esc_url( get_permalink( get_the_ID() ) ),
              sprintf( __( 'Continue reading %s', 'wpdocs' ), '<span class="screen-reader-text">' . get_the_title( get_the_ID() ) . '</span>' )
        );
    }
    add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );

  2. Skip to note 7 content

    Example migrated from Codex:

    To change excerpt more string, add the following code to functions.php file in your theme:

    function custom_excerpt_more( $more ) {
    	return '[.....]';
    }
    add_filter( 'excerpt_more', 'custom_excerpt_more' );

    For versions older than 2.9 use:

    function custom_excerpt_more( $excerpt ) {
    	return str_replace( '[…]', '...', $excerpt );
    }
    add_filter( 'wp_trim_excerpt', 'custom_excerpt_more' );

  3. Skip to note 8 content

    Add A “Read more” with post link.

       function wpdocs_custom_excerpt_more( $more ) { 
       $more = '<a href="' . get_post_permalink() .'" rel="nofollow ugc"> … Read more </a>';
       return $more;
    }
    
    add_filter( 'excerpt_more', 'wpdocs_custom_excerpt_more' );