Change default excerpt length for different categories

By default, WordPress will set you excerpts to 55 words and those words will be shown as short summary to your readers. This number may have been changed by the theme you are using, but if you want to control the way excerpts are displayed on your WP website, you can easily set your own number of words.

In some cases, setting the same excerpt length won’t be much of a help. There will be categories which will require more words in excerpts and those that will require shorter ones. Because this is site specific, you will have to enter categories manually, but the following function will help you deal with the problem.

The first example will let you choose one category for which you want to set different excerpt length. Choose that category, define number of words for its excerpt and the number of words for all other categories’ excerpt:

  1. Open functions.php
  2. Copy and paste this function:
  3. function excerpt_length_category( $length ) {
    if ( in_category( 'Reviews' ) ) {
    return 20;
    } else {
    return 60;
    }
    }
    add_filter( 'excerpt_length', 'excerpt_length_category' );
    
  4. Change category name on 2nd line
  5. Change length of excerpts (number of words) for that category on line #3
  6. Change length of all other categories on line #5
  7. Save changes
  8. While this will be more than enough in order to change excerpt length for that one category that bothers you, it won’t help you much if you need to define the length for several categories at once. In that case, you will be needing the following:

    function excerpt_length_category( $length ) {
    if ( in_category( 'Review' ) ) {
    return 35;
    } elseif ( in_category( array( 'News', 'Videos', 'Editorial' ) ) ) {
    return 60;
    } else {
    return 55;
    }
    }
    add_filter( 'excerpt_length', 'excerpt_length_category' );
    

    This function will allow you to set different excerpt lengths for different categories and still let you choose the default one.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

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