If you are a WordPress theme developer, you know that the_content function displays all the words whenever you use it. In this short tips and trick tutorial, you will learn how to limit WordPress the_content words length . We will show you the different ways to do that plus the best and recommended way.
How to Limit WordPress the_content Words
You use the_content function in almost every page of your WordPress theme. For instance you use in index.php file and it will echo all the content for one post or page. But you don’t want to show all content. Maybe only 50 words. Here how you can limit the_content.
Using Filter Hoock
Open your functions.php file and write the following code.
function technig_the_content($content) { // Take the existing content and return a subset of characters it return substr($content, 0, 500); } add_filter("the_content", "technig_the_content");
The only problem with this method is that, it will filter the_content and shows 500 character no-matter where you have used. For example, if you have used in in single post which you display all the content, it will display only that 500 characters. ( not a good way )
Using wp_trim_words
This method is probably easy and short solution. Every time you use the_content function, apply the wp_trim_words function on it.
<?php echo wp_trim_words( get_the_content(), 80 ); ?>
You can’t use the_content function because you it will echo the content directly. Instead, we use get_the_content() function.
Using Custom Function
This method is going to be the best and most flexible way to limit WordPress the_content words length. Write the following custom function in your functions.php file.
function technig_content($limit){ $content = explode(' ', get_the_content(), $limit); if (count($content)>=$limit){ array_pop($content); $content = implode(" ",$content).'...'; } else { $content = implode(" ",$content); } $content = preg_replace('/\[.+\]/','', $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); return $content; }
Use the custom function instead of the_content. For example:
<?php echo technig_content(30); ?>
Conclusion
You can use the_excerpt() function as will to display less content. But still you will need to modify the length of the words in that. We hope you have learn something and use it in you next project. Feel free to ask you question bellow. 🙂
Thank you, this helped a great deal!
This pulls in images as well as text is there away to only pull in text?