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.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
You could use a Wordpress filter callback function. In your theme's directory, create a file called
functions.php
and add the following in:The
plugin_myContentFilter()
function will be called each time you request the content of a post/page 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 do the same for
the_exercpt()
-add_filter()
and then a function to be used as a callback.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.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.
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)wp_trim_words
This function trims text to a certain number of words and returns the trimmed text.Example:-
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: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 withget_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>'