Last updated on September 13, 2023

Change Excerpt Length

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Change the default length of the excerpt.

To change the length of the excerpt in WordPress, you can use the excerpt_length filter in your theme’s functions.php file. The following code snippet will change the excerpt length to 20 words:

function wpsnippets_custom_excerpt_length( $length ) {
    return 20;
}

add_filter('excerpt_length', 'wpsnippets_custom_excerpt_length');

This code sets the excerpt length to 20 words by returning a value of 20 from the wpsnippets_custom_excerpt_length function. You can adjust the number to your desired length.

If you want to change the excerpt length only for a specific post type, you can use the get_post_type function to check the post type before setting the excerpt length. For example, the following code sets the excerpt length to 30 words for posts:

function wpsnippets_custom_excerpt_length( $default_length ) {

    if ( get_post_type() === 'post' ) {
        return 30;
    } else {
        return $default_length;
    }
}

add_filter( 'excerpt_length', 'wpsnippets_custom_excerpt_length' );

This code checks if the current post type is post, and if it is, sets the excerpt length to 30 words. If the current post type is not post, it returns the default excerpt length.

Last updated on September 13, 2023. Originally posted on May 3, 2023.

Leave a Reply