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.

1 Answer 1

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 );
3
  • this doesn't work. Ie., it's not executed at all. Funny thing, wp_trim_excerpt nor get_the_excerpt are being called at all, from what I can see. Only the_excerpt gets called.
    – errorous
    Commented Jun 14, 2020 at 13:33
  • Hi Milos. Are you sure you put the code in the right file/place, e.g. the root of the theme functions.php? Have you done something with the $excerpt, e.g. $excerpt .= ' testt'; ? Have you tried disabling plugins? Are you sure the post does not actually have a custom excerpt?
    – Sally CJ
    Commented Jun 15, 2020 at 0:12
  • This was DiVi theme. It obviously overrode the original process for creating an excerpt.
    – errorous
    Commented Jun 15, 2020 at 0:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.