With the release of newer version of WordPress, quite often we are getting newer functions to make our life lot easier. Today I will talk about once such function that can be extremely useful for many reason. I will focus on a function called “wp_trim_words” which can be used in the following format or with little modification which I will talk about little later.
<?php $trimmed = wp_trim_words($text, $num = 55, $more = null); echo $trimmed; ?>
As you can see, this function takes three different parameters. With $text variable, this function takes the input text which could of any length. On our second parameter $num, we are defining the number of words that we are willing to break our text into. At the end are defining $more, which can either be a link or a simple symbol or text to indicate the rest of the text. You really really can get creative on this portion.
So, let’s get started and see how we can use “wp_trim_words” function with some example.
In order to display the post excerpt on our archive page (mostly) or anywhere else, we use “the_excerpt” function directly. However, if you want to trim down the excerpt content of your post our new function could be really useful. This is how you can use it within the loop.
<?php echo wp_trim_words(get_the_excerpt(), 3, '...'); ?>
For simplicity, I didn’t assign any variable to our function rather I echoed it right away.
In similar fashion, we can trim down the post content as well. Generally we use the_content function to get the full text of our post. However, when we want to trim the text, we should use get_the_content function. This is how it should be used.
<?php echo wp_trim_words(get_the_content(), 20, '...'); ?>
Yes sir! you can trim post title as well, if you want to for some weird reason. Simply change “the_title” function with “get_the_title“. This is how it should be done.
<?php echo wp_trim_words(get_the_title(), 20, '...'); ?>
You get the idea, didn’t you?
What about Permalink?
Just in case if you want to place a link for full text page after the trimmed down version of your coent, you can do it like this.
<?php echo wp_trim_words(get_the_excerpt(), 3, ' <a href="'.get_the_permalink().'">more</a>'); ?>
I hope you will find this post useful. Got any question? feel free to drop a line from the comment section below.