Customizing the_excerpt()

Change the default number of words returned by the_excerpt() using this function:

// excerpt length 
function custom_excerpt_length( $length ) {
 return 30;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Sourced here.

I’ve recently run into issues with the above not working  in all Themes, and have not yet found out why. Here is another method to customize the excerpt that worked instead:

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;
}

function content($limit) {
      $content = explode(' ', get_the_content(), $limit);
      if (count($content)>=$limit) {
        array_pop($content);
        $content = implode(" ",$content).'...';
      } else {
        $content = implode(" ",$content);
      } 
      $content = preg_replace('/\[.+\]/','', $content);
      $content = apply_filters('the_content', $content); 
      $content = str_replace(']]>', ']]>', $content);
      return $content;
}

Display in template:

<?php echo excerpt(25); ?>

Source.


Change the “Read More” excerpt text:

// Replaces the excerpt "Read More" text by a link
function new_excerpt_more($more) {
       global $post;
 return '<a class="moretag" href="'. get_permalink($post->ID) . '"> Read the full article...</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');

Be as complex, or as simple as you want:

// excerpt text
function new_excerpt_more($more) {
       global $post;
       return ' ...';
}
add_filter('excerpt_more', 'new_excerpt_more');

Sourced here.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.