Wordpress 标题:如果长度超过 50 个字符,则显示省略号

2022-08-30 17:56:59

我有一个带有标题的WordPress网站,如果标题超过50个字符,我需要在标题末尾添加一个省略号(),并将标题停止在50个字符处。...

以下是我正在编写的PHP,但它似乎无法正常工作。

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

答案 1

mb_strimwidth函数正是这样做的。

echo mb_strimwidth(get_the_title(), 0, 50, '...');

答案 2

WordPress内置功能,可以根据您提供的单词数量修剪句子,如果您想按单词修剪,那么此功能可能会对您有所帮助。"wp_trim_words()"

https://codex.wordpress.org/Function_Reference/wp_trim_words

要修剪长度超过5个单词的标题,您可以这样做

<?php
$title = get_the_title();
$short_title = wp_trim_words( $title, 5, '...' );
echo '<h3>'.$short_title.'</h3>';
?>

推荐