Multiple Excerpt Lengths in WordPress

You may or may not know that you can change or set the excerpt length in WordPress using the following filter:

function sv_excerpt_length( $length ) {
    return 15;
}
add_filter( 'excerpt_length', 'sv_excerpt_length' );

But that sets one excerpt length every time you use the the_excerpt function. What if you want different excerpt lengths in different places in your theme? In that case, you can use the following code in functions.php:

function excerpt($limit) {
      $excerpt = explode(' ', get_the_excerpt(), $limit);

      if (count($excerpt) >= $limit) {
          array_pop($excerpt);
          $excerpt = implode(" ", $excerpt) . '...';
      } else {
          $excerpt = implode(" ", $excerpt);
      }

      $excerpt = preg_replace('`[[^]]*]`', '', $excerpt);

      return $excerpt;
}

Then you can set the excerpt length in your theme like this:

<?php echo excerpt(25); ?>
Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!