Change Excerpt Length For Different Categories

How to Change Excerpt Length For Different Categories

in Categories
Google+ LinkedIn

Do you ever wonder how you could be able to change excerpt length based on category the post belongs to. In this article we will be discussing how to change excerpt length for different categories.

Post excerpt has a default length of 55 words but sometimes you want to modify this limit for certain category posts without effecting all post from other categories. For example if you have a news website and you want to display news posts from ‘Breaking News’ category with lesser words in excerpt but still want all other category news to have normal excerpt. So here is a code snippet to do just that.

Simply paste the code snippet into your functions.php file. But don’t forget to change the category name ‘Breaking News’ with yours in following snippet. Also it’s worth mentioning that in following snippet you are not limited to only specify category names in template tag in_category but you can specify category ID (integer), name or slug (string), or an array of these. For example instead of in_category( ‘Breaking News’ ), you can use in_category( 10 ) or in_category( ‘breaking-news’ ).

// change excerpt length for different categories
function wcs_excerpt_length_category( $length ) {
    if ( in_category( 'Breaking News' ) ) {
        return 20;
    } else {
        return 60;
    }
}
add_filter( 'excerpt_length', 'wcs_excerpt_length_category' );

Here is a more detailed example on how to change excerpt length for different categories. In this following code snippet we are defining excerpt length of 20 words for category ‘Breaking News’, 40 words for category ‘Politics’, ‘Technology’, ‘Sports’ and keep 60 words as default excerpt length.

// change excerpt length for different categories
function wcs_excerpt_length_category( $length ) {
    if ( in_category( 'Breaking News' ) ) {
        return 20;
    } elseif ( in_category( array( 'Politics', 'Technology', 'Sports' ) ) ) {
        return 40;
    } else {
        return 60;
    }
}
add_filter( 'excerpt_length', 'wcs_excerpt_length_category' );

Share the love

If you like this snippet, share it with others!

Leave a Reply

Your email address will not be published. Required fields are marked *