Friday, August 03, 2012

Wordpress: limit string words and add continue_read_link

I am using twenty theme in Wordpress, and I wanted to limit the number of words. I found the string_limit_words function, but I wanted to add continue_reading_link. Below is the code that I used
http://wordpress.org/support/topic/limit-the-number-of-words-in-excerpt-without-plugins
Add the following code in functions.php in your theme folder (e.g. /wp-contents/themes/twentyten/functions.php).
/* for limiting string words */
function string_limit_words($string, $word_limit)
{
  $words = explode(' ', $string, ($word_limit + 1));
  if(count($words) > $word_limit)
  array_pop($words);
  return implode(' ', $words);
}

function get_excerpt($count){
  $permalink = get_permalink($post->ID);
  $excerpt = get_the_excerpt();
  $excerpt = string_limit_words($excerpt, $count);
  $excerpt = $excerpt.'... '.twentyten_continue_reading_link();
  return $excerpt;
}

If you are not using twentyten theme, you can look for the function that creates continue_reading_link or use the following code instead.

function get_excerpt($count){
  $permalink = get_permalink($post->ID);
  $excerpt = get_the_excerpt();
  $excerpt = string_limit_words($excerpt, $count);
  $excerpt = $excerpt.'...  <a href="'. get_permalink() . '">' . __( 'Read More', 'PUT_YOUR_THEME_NAME_HERE' ) . '</a>';   
  return $excerpt;
}


And in index.php or the page where you want to limit the excerpt words, put the following code
echo get_excerpt(125);
Please take note that 125 is the number of words, not number of characters.

No comments: