How to set character limit on the_content() and the_excerpt() in wordpress

You could use a Wordpress filter callback function. In your theme's directory, locate or create a file called functions.php and add the following in:

<?php   
  add_filter("the_content", "plugin_myContentFilter");

  function plugin_myContentFilter($content)
  {
    // Take the existing content and return a subset of it
    return substr($content, 0, 300);
  }
?>

The plugin_myContentFilter() is a function you provide that will be called each time you request the content of a post type like posts/pages via the_content(). It provides you with the content as an input, and will use whatever you return from the function for subsequent output or other filter functions.

You can also use add_filter() for other functions like the_excerpt() to provide a callback function whenever the excerpt is requested.

See the Wordpress filter reference docs for more details.


Or even easier and without the need to create a filter: use PHP's mb_strimwidth to truncate a string to a certain width (length). Just make sure you use one of the get_ syntaxes. For example with the content:

<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>

Update 2022

mb_strimwidth breaks the HTML if the comment tag is used. use official wordpress wp_trim_words functions

<?php $content = get_the_content(); echo wp_trim_words( get_the_content(), 400, '...' );?>

This will cut the string at 400 characters and close it with .... Just add a "read more"-link to the end by pointing to the permalink with get_permalink().

<a href="<?php the_permalink() ?>">Read more </a>

Of course you could also build the read more in the first line. Than just replace '...' with '<a href="' . get_permalink() . '">[Read more]</a>'

Tags:

Php

Wordpress