Trim Excerpts and Content Directly in Your Child Theme Templates – No Need to Deal With Functions.php

I’ve desperately tried to change excerpts words limit in my TwentyTwelve WordPress child theme, with no success. Then I found this post to limit excerpts and other content directly in a template page code. It’s using a new wp_trim_words() feature.

So instead of using the_excerpt(); in template itself we can use this trimming code:

<?php 
$trimexcerpt = get_the_excerpt();
$shortexcerpt = wp_trim_words( 
  $trimexcerpt,
  // limit number of words 
  $num_words = 28,
  // design your read more link 
  $more = '… <a href="' . get_permalink() . '">more</a>' ); 
// show excerpt with read more link
echo '<p>' . $shortexcerpt . '</p>'; 
?>

Same can work for other elements on template page, i.e. Post Title

<?php //limit some linked title to 4 words
$trimtitle = get_the_title();
$atitle = wp_trim_words( 
  $trimtitle, 
  $num_words = 4, 
  $more = '…' );
// show truncated title with a link
echo '<a href="' . get_permalink() . '">' . $atitle . '</a>';
?>

Great and useful feature!

Share:
This entry was posted in WordPress and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *