Advertisement
salmancreation

Limit the number of words in excerpt without plugins

Jan 8th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.75 KB | None | 0 0
  1.  
  2. Limit the number of words in excerpt without plugins
  3.  
  4. Excerpt by default display a numbers of characters so some times brake a word, No you can set limit the number of words displayed in the excerpt without any plugin.
  5.  
  6. Put the following code in your templates functions.php file.
  7. 1
  8. 2
  9. 3
  10. 4
  11. 5
  12. 6
  13. 7
  14.    
  15. function royal_string_limit_words($string, $word_limit)
  16. {
  17.   $words = explode(' ', $string, ($word_limit + 1));
  18.   if(count($words) > $word_limit)
  19.   array_pop($words);
  20.   return implode(' ', $words);
  21. }
  22.  
  23. Now put the following code in your template where you want to display the excerpt.
  24. 1
  25. 2
  26. 3
  27. 4
  28.    
  29. <?php
  30.   $excerpt = get_the_excerpt();
  31.   echo royal_string_limit_words($excerpt,55);
  32. ?>
  33.  
  34. Where 55 is the number of words (not character) to display.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement