Trim Any Text In WordPress by Words With wp_trim_words()

WordPressPosted on

1 min read

Limiting our text length in a WordPress theme is always necessary. Mostly in case of the excerpt of our posts; to define it we can use the excerpt_length filter which is a global solution.

For me, the best solution for text trimming in WordPress is the wp_trim_words(). It is easy to use and know anything which is needed for the limiting. It is supported by WP 3.3 and a good multi-tool.

The Parameters of wp_trim_words()

The function gets three parameters:

  • $text (string)(required): the text to trim
  • $num_words (int)(optional): the number of words (default value: 55)
  • $more (string)(optional): what to append if the $text is too long so the trimming is needed. Mostly this is the ellipsis: … (default value: null)
<div class="list-item">
    <p class="list-item__excerpt">
        <?php echo wp_trim_words( get_the_excerpt(), 25, '...' ); ?>

This way we can easily limit any text in our themes which can be neat. Using it, we can set separate options for more than one text section in our Customizer to make our themes a little bit better for the users. For the full reference, please visit the official documentation!

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in WordPress category