WordPress change default excerpt length

Excerpt is the easiest way to display trimmed down version of full description of a wordpress post. You can display excerpt by simply use the_excerpt(); function anywhere in your theme files. By default wordpress has set the excerpt length to 55 words. So, it is important for wordpress developers to know a way to change default excerpt length of wordpress post as in theme development we can’t limit to 55 words.

I’m going to share a function which you can change default excerpt length in this article.

Change Excerpt Length to a fixed value

You can simply change the default excerpt length value to another value. In this case, the excerpt length is a static value throughout the website, but the value is different to the default one. To do that you can simply add following code to the functions.php file in your wordpress theme.

function your_theme_excerpt_length($length) {
    return 200;
add_filter('excerpt_length', 'your_theme_excerpt_length');

And simply call to the_excerpt() function as you do it with default excerpt length.

But it is better to have a way to use different excerpt length values throughout the theme. ie. it is very useful if you can call to the excerpt by passing excerpt length as a parameter of the function.

Calling to the_excerpt function passing excerpt length as a function parameter

In the following function, excerpt length is taken as a parameter of the function. And replace default excerpt length with it. And also “Read More” link also altered according to my need. You can alter it to match your needs. Simply add following code to the functions.php file of your wordpress theme.

function custom_excerpt($excerpt_length = 55, $id = false, $echo = true) {
    $text = '';
    if($id) {
        $the_post = & get_post( $my_id = $id );
        $text = ($the_post->post_excerpt) ? $the_post->post_excerpt : $the_post->post_content;
    } else {
        global $post;
        $text = ($post->post_excerpt) ? $post->post_excerpt : get_the_content('');

    $text = strip_shortcodes( $text );
    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]&gt;', $text);
    $text = strip_tags($text);

    $excerpt_more = ' ' . '<a href="'. get_permalink($id) . '">Read More...</a>';
    $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
    if ( count($words) > $excerpt_length ) {
        $text = implode(' ', $words);
        $text = $text . $excerpt_more;
    } else {
        $text = implode(' ', $words);
        echo apply_filters('the_content', $text);
        return $text;

and call to the function anywhere you want to display excerpt in your theme files.


Thats it! we are done! Try it and share your thoughts bellow.