How do I set a character limit on the_content() and the_excerpt() in wordpress? I have only found solutions for the word limit – I want to be able to set an exact amount characters of outputted.
Leave a Reply
You must be logged in to post a comment.
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 theget_
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 wordpresswp_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()
.Of course you could also build the
read more
in the first line. Than just replace'...'
with'<a href="' . get_permalink() . '">[Read more]</a>'
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: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 viathe_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 likethe_excerpt()
to provide a callback function whenever the excerpt is requested.See the WordPress filter reference docs for more details.
wp_trim_words
This function trims text to a certain number of words and returns the trimmed text.Example:-
This also balances HTML tags so that they won’t be left open and doesn’t break words.
For Using
the_content()
functions (for displaying the main content of the page)For Using
the_excerpt()
functions (for displaying the excerpt-short content of the page)Replace
<?php the_content();?>
by the code belowphp substr() function refrence
php strip_tags() function refrence
wp_trim_words()
This function trims text to a certain number of words and returns the trimmed text.Get truncated string with specified width using
mb_strimwidth()
php function.Using
add_filter()
method of WordPress onthe_content
filter hook.Using custom php function to limit content characters.
just to help, if any one want to limit post length at
home page
.. then can use below code to do that..the below code is simply a modification of
@bfred.it
SirI know this post is a bit old, but thought I would add the functions I use that take into account any filters and any
<![CDATA[some stuff]]>
content you want to safely exclude.Simply add to your functions.php file and use anywhere you would like, such as:
content(53);
or
excerpt(27);
Enjoy!