How to limit WordPress post content length?

Use wp_trim_words() to cut a text to a number of words, and the excerpt_length filter to change the length of automatic excerpts.

$content = 'WordPress is a free and open source CMS. It runs a large part of the web and has thousands of themes and plugins for every kind of site.';

echo wp_trim_words( $content, 10, '...' ) . "\n";
echo wp_html_excerpt( $content, 40, '...' ) . "\n";
echo mb_strimwidth( $content, 0, 40, '...' );
Output

WordPress is a free and open source CMS. It runs…
WordPress is a free and open source CMS….
WordPress is a free and open source C…

  • wp_trim_words( $text, $num_words, $more ): counts words, and removes the HTML tags.
  • wp_html_excerpt( $str, $count, $more ): counts characters, and removes the HTML tags.

To change the length of the automatic excerpt (used by the_excerpt()), add a filter in functions.php:

add_filter( 'excerpt_length', function () {
	return 20; // words
}, 999 );

add_filter( 'excerpt_more', function () {
	return '...';
} );

Inside the loop you can use it with the content: echo wp_trim_words( get_the_content(), 30 );. The default excerpt is 55 words.


Learn more about the similar topics:
Tutorials
WordPress Posts
WordPress Pages
WordPress Block Editor (Gutenberg)
WordPress Categories and Tags
WordPress Media Library
WordPress Comments
Exercises & Assignments
Add categories, a child category and a tag to a post
Interview Questions & Answers
How to limit WordPress post content length?
What is the difference between Posts & Pages in WordPress?
Which Gutenberg blocks support wide and full width alignment?
What is Post Status in WordPress?
What is the difference between categories and tags in WordPress?
What is Gutenberg in WordPress?