Wordpress Titles: If Longer Than 50 Characters, Sh

2019-03-11 02:09发布

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, seeking a PHP guru to teach me the correct way for this. Any help would be greatly appreciated.

<?php if (strlen("the_title()") > 50) { ?>
                <?php the_title(); ?>
            <?php } if (strlen("the_title()") < 50) { ?>
                <?php echo substr(get_the_title(), 0, 50); ?>...
            <?php } ?>   

标签: php wordpress
8条回答
Summer. ? 凉城
2楼-- · 2019-03-11 02:33
echo (strlen(the_title())>50) ? (substr(the_title(), 0, 50) . "...") : the_title());

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 from the_title().

You can read more about substr here: http://php.net/manual/en/function.substr.php

You can find info on the ternary operator here: http://php.net/manual/en/language.operators.comparison.php

查看更多
聊天终结者
3楼-- · 2019-03-11 02:36

The mb_strimwidth function does exactly that.

echo mb_strimwidth(get_the_title(), 0, 50, '...');
查看更多
登录 后发表回答