I have a WordPress site with titles, and if the title has more than 50 characters I need to add an ellipsis (...
) at the end of the title and stop the title at 50 characters.
Below is the PHP I am writing but it seems to not work correctly.
<?php if (strlen("the_title()") > 50) { ?>
<?php the_title(); ?>
<?php } if (strlen("the_title()") < 50) { ?>
<?php echo substr(get_the_title(), 0, 50); ?>...
<?php } ?>
The mb_strimwidth function does exactly that.
WordPress has built in function
"wp_trim_words()"
to trim the sentences based on the number of words you provide, If you want to trim by words then this function may help you.https://codex.wordpress.org/Function_Reference/wp_trim_words
to trim the title longer than 5 words you can do this
Single Code, 100% working
PHP Function mb_strimwidth() | WordPress Function get_the_title()
Add this to your “functions.php” file in your theme folder….
then call the title like as follows
You’re checking the length of the string
"the_title()"
. Remove the quotes, and it will probably work (I’m not 100% sure of the difference between the_title() and get_the_title(), as I haven’t used WordPress in a while — you might have to switch that around too):or maybe
Take
the_title()
out of quotes when using thestrlen()
function.This is a ternary operator. What it basically says is if the result from
the_title()
is more than 50 characters, then echo the first 50 characters and then the string...
. Otherwise, just echo the result fromthe_title()
.You can read more about
substr
here: http://php.net/manual/en/function.substr.phpYou can find info on the ternary operator here: http://php.net/manual/en/language.operators.comparison.php
use ‘strlen’