zeshan-a
12/30/2015 - 5:46 AM

Limit WordPress excerpt length by character and keep last word complete, i.e., instead of 'compat...' show full last word, i.e. 'compatibili

Limit WordPress excerpt length by character and keep last word complete, i.e., instead of 'compat...' show full last word, i.e. 'compatibility...'.

// Excerpt - Limit Length by Characters and Keep Last Word Complete.
// Solution from:
// https://wordpress.org/support/topic/limit-excerpt-length-by-characters#post-2248039
// ================================================================================

function excerpt_character_length( $excerpt ){
  $permalink = get_permalink($post->ID);
  $excerpt   = get_the_content();
  $excerpt   = preg_replace(" (\[.*?\])",'',$excerpt);
  $excerpt   = strip_shortcodes($excerpt);
  $excerpt   = strip_tags($excerpt);
  $excerpt   = substr($excerpt, 0, 40);
  $excerpt   = substr($excerpt, 0, strripos($excerpt, " "));
  $excerpt   = trim(preg_replace( '/\s+/', ' ', $excerpt));
  $excerpt   = $excerpt . '... <a class="more-link" href="' . $permalink . '">Read More</a>';
  return $excerpt;
}

add_filter('the_excerpt', 'excerpt_character_length');