Always have “Read More” on Manual and Automatic excerpts

March 22, 2011 – 3:04 pm |

Previously, we have talked about modifying your post excerpts. This is great if you always use the automatic excerpts that WordPress provides.  However, if your customer every puts in a manual excerpt, this functionality won’t give you the “read more” that you are expecting. What a pain, right!?

Well, I have added a new function that I found here and modified it slightly to always have the read more link.  Just add this to your theme’s functions.php file:

  1. <?php
  2. function new_excerpt_more($more) {
  3.     global $post;
  4.  return '… <a href="'. get_permalink($post->ID) . '">&raquo; Read More</a>';
  5. }
  6. add_filter('excerpt_more', 'new_excerpt_more');
  7.  
  8. function new_excerpt_length($length) {
  9.  return 120;
  10. }
  11. add_filter('excerpt_length', 'new_excerpt_length');
  12.  
  13.  
  14. function wp_trim_all_excerpt($text) {
  15.    // Creates an excerpt if needed; and shortens the manual excerpt as well
  16.    global $post;
  17.    if ( empty($text) ) {
  18.       $text = get_the_content('');
  19.    }
  20.    $text = strip_shortcodes( $text ); // optional
  21.    $text = apply_filters('the_content', $text);
  22.    $text = str_replace(']]>', ']]&gt;', $text);
  23.  
  24.    $text = strip_tags($text);
  25.    $excerpt_length = apply_filters('excerpt_length', 55);
  26.    $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
  27.    $words = preg_split("/[nrt ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
  28.    if (count($words)> $excerpt_length) {
  29.       array_pop($words);
  30.       $text = implode(' ', $words);
  31.    } else {
  32.       $text = implode(' ', $words);
  33.    }
  34.    $text = $text . $excerpt_more;
  35.    return $text;
  36. }
  37.  
  38. remove_filter('get_the_excerpt', 'wp_trim_excerpt');
  39. add_filter('get_the_excerpt', 'wp_trim_all_excerpt');
  40. ?>

Note: This repeats the functionality from our previous post, do not copy/paste both into functions.php – you will see errors.

pixel Always have Read More on Manual and Automatic excerpts

Tagged: , , , , , , , , ,

  • Lionel Loeb

    Hello, good idea, but It’ll be nicer if this code could work for a post and page_id link ! some ideas ?

  • http://twitter.com/mbernier Matt Bernier

    I am not sure what you mean by a page_id link? Can you please provide an example?

    If you use the_excerpt() in your theme, then this function will be called and this code executed every time.