How to Limit the_content Function Text Length in WordPress?

If you are a WordPress theme or plugin developer, you definitely need to know how to limit the_content text length or the excerpt word. There are several tips and tricks that you let you do it. In this tutorial we are going to show you the most common ways to limit the_content text length.

What is the_content Function?

The content is a function in WordPress (the_content) that will show post content in your theme. By default, if you call this function, it will show all the post content, weather in home or blog page or single page. mostly we want to limit the words when we call this function in home page, because we want to show only the summary of the post instead of full content.

How to Limit the_content text length?

Mainly, there are two ways to show a custom words limit in instead of full content; using get_the_content or get_the_excerpt. We will show you both ways and you can use any of them in your project. If you want to know what is the difference between them, refer to this article.

Using get_the_content

Here is the code how to it using get_the_content functions.

function my_content($limit) {

   global $post;
   $permalink = get_permalink($post->ID);
   $readmore = "<a href='$permalink'> View article ... </a>";
  $content = explode(' ', get_the_content(), $limit);
  if (count($content)>=$limit) {
    $content = implode(" ",$content).$readmore;
  } else {
    $content = implode(" ",$content);
  $content = preg_replace('/\[.+\]/','', $content);
  $content = apply_filters('the_content', $content); 
  $content = str_replace(']]>', ']]&gt;', $content);
  return $content;

Now any where you want to show a limit amount of words, you can use the ‘my_content(30)’ function and pass the number of words you want to show.


<?php my_content(40); ?>

Of course you can change the function name from my_content to anything you want.

Using get_the_excerpt

If you have read the article about comparing the_excerpt and the_content, you know where to use the_content and where to use the_excerpt. Here is how you do the above using get_the_excerpt function.

function excerpt($limit) {
	  global $post;
	  $permalink = get_permalink($post->ID);
	  $readmore = "<a href='$permalink'> View article ... </a>";
	  $excerpt = explode(' ', get_the_excerpt(), $limit);
	  if (count($excerpt)>=$limit) {
	    $excerpt = implode(" ",$excerpt).$readmore;
	  } else {
	    $excerpt = implode(" ",$excerpt);
	  $excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
	  return $excerpt;

In the same way, anywhere you want, you can use this excerpt function and give the number of words.


It was this simple. There are some other ways that you can do this, like; using filter hooks to filter the_content, but it will not be as flexible as this methods. We hope it has been informative for you, if you have any question, feel free to comment it below. 🙂

How toWordPress DeveloperWordPress Tips
Comments (0)
Add Comment