posts - Hook for changing excerpt content when excerpt not set

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

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 );

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742347910a4426921.html

相关推荐

  • posts - Hook for changing excerpt content when excerpt not set

    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

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信