钩子文档

get_the_excerpt

💡 云策文档标注

概述

get_the_excerpt 是一个 WordPress 过滤器钩子,用于在从数据库检索文章摘要后、返回给 get_the_excerpt() 函数前进行过滤。它允许开发者自定义摘要内容,例如添加链接或处理缺失摘要。

关键要点

  • 过滤器钩子:get_the_excerpt,用于过滤文章摘要。
  • 参数:$post_excerpt(字符串,文章摘要)和 $post(WP_Post 对象,文章对象)。
  • 用法:通过 add_filter 添加自定义函数,函数必须返回处理后的摘要,否则可能导致显示空白或错误。
  • 注意事项:自定义函数名需唯一,避免与其他函数冲突;从 4.5.0 版本开始引入 $post 参数。
  • 相关函数:与 get_the_excerpt()、excerpt_length 和 excerpt_more 过滤器配合使用。

代码示例

function filter_function_name( $excerpt ) {
    // 处理摘要逻辑
    return $excerpt;
}
add_filter( 'get_the_excerpt', 'filter_function_name' );

注意事项

  • 当摘要存储在变量中时,不会自动应用 excerpt_length 过滤器进行修剪,需手动使用 wp_trim_words()。
  • 使用 wp_trim_words() 时会移除所有 HTML 标签,因为它应用了 wp_strip_all_tags()。
  • 示例包括添加自定义“阅读更多”链接和提供缺失摘要的回退文本。

📄 原文内容

Filters the retrieved post excerpt.

Parameters

$post_excerptstring
The post excerpt.
$postWP_Post
Post object.

More Information

The get_the_excerpt filter is used to filter the excerpt of the post after it is retrieved from the database and before it is returned from the get_the_excerpt() function.

When the get_the_excerpt filter is called, the filter function is passed a single argument containing the post excerpt.

function filter_function_name( $excerpt ) {
# ...
}
add_filter( 'get_the_excerpt', 'filter_function_name' );

Where ‘filter_function_name‘ is the function WordPress should call when the excerpt is being retrieved. Note that the filter function must return the excerpt after it is finished processing, or page sections showing an excerpt will be blank, and other plugins also filtering the excerpt may generate errors.

The ‘filter_function_name‘ should be a unique function name. It cannot match any other function name already declared.

Source

return apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );

Changelog

Version Description
4.5.0 Introduced the $post parameter.
1.2.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    When using this filter on a string stored in a variable, the string will not be trimmed by the excerpt_length filter.

    This is expected behaviour. By passing a long string through the get_the_excerpt filter, you are simulating the case where you have entered the same long text into the Excerpt field in the Edit Post screen. When a custom excerpt is present on the post, no trimming is done (though other content filters are applied).

    If you want to simulate the automatic excerpt trimming on arbitrary text, you can pass the text to wp_trim_words() yourself, with a function like this:

    function wpcodex_format_custom_excerpt( $text ) {
      /**
       * Filters the number of words in an excerpt.
       *
       * @since 2.7.0
       *
       * @param int $number The number of words. Default 55.
       */
      $excerpt_length = apply_filters( 'excerpt_length', 55 );
      /**
       * Filters the string in the "more" link displayed after a trimmed excerpt.
       *
       * @since 2.9.0
       *
       * @param string $more_string The string shown within the more link.
       */
      $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
      $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    
      // Format the text
      $text = apply_filters( 'get_the_excerpt', $text );
    
      return $text;
    }

    The function above can be used like this:

    $text = "Etiam laoreet libero sit amet sem tempor, vel dictum odio bibendum. Aenean odio ligula, placerat sodales dui non, tempor dictum lorem. Vestibulum rutrum, velit a placerat imperdiet, erat massa porta urna, a convallis diam lorem non sapien. Vivamus in risus non quam aliquet blandit nec fermentum dolor. Duis ultricies lectus eu cursus fermentum. Sed eget convallis odio. Ut ut dolor nec nisi varius blandit a eget justo. Integer sed tellus eget leo pretium ultricies. Nullam rhoncus ex sit amet dolor pellentesque feugiat. Nullam a eros orci. Etiam egestas est erat, eu pellentesque sapien dignissim vel. Nulla malesuada commodo justo, at egestas purus egestas fermentum.
    
    Vestibulum vitae metus ullamcorper, vehicula urna eu, ullamcorper leo. Sed sit amet eros eget metus bibendum blandit. Praesent ac lacinia purus. Donec laoreet tempus dui id faucibus. Nulla laoreet cursus laoreet. Nulla et arcu ex. Pellentesque cursus non metus a volutpat. Donec pretium orci et metus molestie, ac feugiat lacus auctor. Ut vehicula eu augue eu gravida. In scelerisque risus in rutrum vestibulum. Phasellus egestas augue quis enim varius, ut sagittis massa auctor.";
    $text = wpcodex_format_custom_excerpt( $text );

  2. Skip to note 5 content

    Examples migrated from Codex:

    Custom “More” Link

    This example from the twentyeleven theme appends a custom “Read more” link to post excerpts. See has_excerpt() and is_attachment().

    /**
     * Adds a pretty "Continue Reading" link to custom post excerpts.
     *
     * To override this link in a child theme, remove the filter and add your own
     * function tied to the get_the_excerpt filter hook.
     */
    function twentyeleven_custom_excerpt_more( $output ) {
      if ( has_excerpt() && ! is_attachment() ) {
        $output .= twentyeleven_continue_reading_link();
      }
      return $output;
    }
    add_filter( 'get_the_excerpt', 'twentyeleven_custom_excerpt_more' );

  3. Skip to note 6 content

    Fallback excerpt for posts with AUTOMATED excerpt:

    /**
    * Filters the retrieved post excerpt.
    *
    * @param string  $post_excerpt The post excerpt.
    * @param WP_Post $post         Post object.
    */
    function wpdocs_excerpt_fallback( $post_excerpt ) {
    	if ( ! $post_excerpt ) {
    		return '(no excerpt present, click "read more" to view post)';
    	}
    	return $post_excerpt;
    }
    add_filter( 'get_the_excerpt', 'wpdocs_excerpt_fallback' );