• Skip to primary navigation
  • Skip to content

Peter Shilling

A blog about WordPress, Apple, Music & Photos

  • About
  • Blog
    • WordPress
    • Apple
  • Contact
You are here: Home / WordPress / WordPress Code / WordPress: control the length of excerpts or comments

WordPress: control the length of excerpts or comments

April 11, 2012 by Peter Leave a Comment

It’s a common problem when designing WordPress themes, you need to control the amount of text that is going to populate a certain area of the layout. Regardless if it’s the except or the comment that your printing to screen this great little PHP snippet will do the job. I originally found this posted here on Stuart Duff’s blog.

function string_limit_words($string, $word_limit)
{
 $words = explode(' ', $string, ($word_limit + 1));
 if(count($words) > $word_limit)
 array_pop($words);
 return implode(' ', $words);
}

So the above code lives in your functions.php file or elsewhere in your theme, then use this snippet below to run it.

$excerpt = get_the_excerpt();
echo string_limit_words($excerpt,40);

So this works for the except but can be used in other places, recently I had a situation where I’m printing the comments on the home page for a site and wanted to trim them down.
The function can be used in this situation as well, see below.

$args = array(
 'status' => 'approved',
 'number' => '5'
 );
 $comments = get_comments($args);
 echo "<ul>";
 foreach($comments as $comment) :
 echo '<li>';
 echo $comment->comment_author;
 echo " on ";
 echo "<a href=" . get_permalink($comment->comment_post_ID ) . ">";
 echo get_the_title($comment->comment_post_ID);
 echo "</a>";
 echo "<p class='ucomment'>";
 $comment = $comment->comment_content;
 echo string_limit_words($comment,40);

 echo "</p>";
 echo "</li>";
 endforeach;
 echo "</ul></div>";
 // end - show lastest 5 comments from all posts

Leave a Reply

Be the First to Comment!

avatar
wpdiscuz_captcharefresh
avatar
wpdiscuz_captcharefresh
  Subscribe  
Notify of
  • LinkedIn
  • Twitter
  • Google Plus
  • RSS

Copyright ©2019 · Peter Shilling - All Rights Reserved ·