FriendlyWP
10/26/2013 - 12:44 AM

Display content with a word limit

Display content with a word limit

/**
 * Display specified content with a word limit
 * Can be used for excerpts, full content, etc.
 * In your theme file, use thus to display 40 words of the excerpt:
 *  $excerpt = get_the_excerpt(); 
 *  echo string_limit_words( $excerpt, 40 );
 *
 * @param string $string A variable containing the content you wish to display.
 * @param num $word_limit The number of words to display.
 * @return string Content limited to the number of words specified.
 */
 
function string_limit_words( $string, $word_limit ) {
  $words = explode(' ', $string, ($word_limit + 1));
  if(count($words) > $word_limit)
  array_pop($words);
  return implode(' ', $words);
}