Sometimes we may need to show limited or extra excerpt content for posts from some specific category/taxonomy. We can easily control excerpt length using the_excerpt
filter. And with help from has_term
function, we can define separate length for one or more specific categories.
function careless_trim_custom_excerpt( $excerpt ) {
//only for specific category/taxonomy
if ( has_term( array( '123', '234' ), 'category' ) ) {
$excerpt = wp_trim_words( get_the_excerpt(), 10 );
}
return $excerpt;
}
add_filter( 'the_excerpt', 'careless_trim_custom_excerpt', 999 );
In the above code, line 3 defines our categories or custom taxonomies. Replace 123
and 234
with your desired category/taxonomy ID. Here, category
is the taxonomy. If you want this for WooCommerce, replace category
with product_cat
.
Line 4 defines number of words to show as excerpt. Replace 10
with your desired number.
Code goes in the functions.php
file of your active theme.