Archived topic
Remove automatic excerpts from single posts only
5 replies · Started by George on October 18, 2022
I am using a dynamic excerpt headline in my author meta template element. I want to remove automatic excerpts from single posts but keep excerpts with custom excerpt content. I am using this code:
remove_filter('get_the_excerpt','wp_trim_excerpt');
But it removes automatic excerpts from all category archives as well which I need. This code here doesn't do anything.
if ( is_single() && 'post' == get_post_type() ) {
remove_filter('get_the_excerpt','wp_trim_excerpt');
}
I've also tried this code:
add_filter( 'excerpt_length','lh_custom_category_excerpt_length', 1000 );
function lh_custom_category_excerpt_length( $length )
{
if ( is_single() && 'post' == get_post_type() ) {
return 0;
}
return $length;
}
but it leaves three dots ... in place of the automatic excerpt.
Hi George,
try this:
1. Select the headline block that is displaying the Excerpt, and in Advanced > Addtional CSS Class(es) add a custom class eg. single-post-excerpt
2. Then add this PHP Snippet
add_filter( 'render_block', function( $block_content, $block ) {
if ( !is_admin()
&& is_single()
&& ! has_excerpt()
&& ! empty( $block['attrs']['className'] )
&& strpos( $block['attrs']['className'], 'single-post-excerpt' ) !== false
) {
$block_content = null;
}
return $block_content;
}, 10, 2 );
It uses the has_excerpt() function, to determine if the post has a custom excerpt, if it does not (!) then it strips the block content for the headline with the single-post-excerpt class.
Ah, I see what you did. Perfect, it works, thanks!
Glad to be of help :)
I will also leave this here in case it might seem useful to users in the future. I was made aware that possibly the code runs too early, i.e. before WordPress determined what the queried object is, i.e. whether it's for a single post, a category archive, a search results page, etc.
Putting the code inside a function which is hooked on wp also solves the issue:
add_action( 'wp', function () {
if ( is_single() && 'post' == get_post_type() ) {
remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
}
} );
Thanks again for the solution, David.
Awesome - thanks for sharing that George!