最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

posts - Hook for changing excerpt content when excerpt not set

programmeradmin1浏览0评论

Title says pretty much all of it. I need a filter that I can use to change excerpt content for those posts that have no excerpt set.

Now, I've tried both the_excerpt and get_the_excerpt, they both pass one parameter, and in both cases said parameter is empty string.

That said, I will need to hook onto a filter that has access to the auto-generated except, and lets me change it.

Title says pretty much all of it. I need a filter that I can use to change excerpt content for those posts that have no excerpt set.

Now, I've tried both the_excerpt and get_the_excerpt, they both pass one parameter, and in both cases said parameter is empty string.

That said, I will need to hook onto a filter that has access to the auto-generated except, and lets me change it.

Share Improve this question asked Jun 14, 2020 at 8:57 errorouserrorous 1691 silver badge9 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

The proper hooks for modifying the post excerpt are the ones you already tried: get_the_excerpt and the_excerpt, and WordPress actually uses the former one to generate an excerpt from the full post content, if there's no custom or manually-specified excerpt for the post — below is the relevant code in wp-includes/default-filters.php:

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

So if you want to access the auto-generated excerpt, then with the the_excerpt hook, you can do it like so:

add_filter( 'the_excerpt', function ( $excerpt ) {
    return has_excerpt() ?
        'Has custom excerpt: ' . $excerpt :
        'Automatic excerpt: ' . $excerpt;
} );

But take note, the automatic excerpt may not necessarily be the one initially generated by WordPress and WordPress might not even be the one that generated the excerpt — plugins could have completely overridden it or just customized it, just as you can do the same.

And as you may have guessed it, you can remove the default WordPress filter and then use your own callback to generate your own "automatic" excerpt:

remove_filter( 'get_the_excerpt', 'wp_trim_excerpt', 10, 2 );

add_filter( 'get_the_excerpt', function ( $excerpt, $post ) {
    return $post->post_excerpt ?
        'Has custom excerpt: ' . $excerpt :
        'Here, create your own excerpt.';
}, 10, 2 );
发布评论

评论列表(0)

  1. 暂无评论