开发者

Wordpress/PHP: Shorten title if title characters are more than 8 characters

开发者 https://www.devze.com 2023-01-30 17:13 出处:网络
I am trying to learn how to shor开发者_如何学Goten a title only if it is over 8 characters long. If it is longer than 8 characters, then echo the first 8 characters and put an ellipse after it.

I am trying to learn how to shor开发者_如何学Goten a title only if it is over 8 characters long. If it is longer than 8 characters, then echo the first 8 characters and put an ellipse after it.

Here is how I am getting the title:

<?php echo $post->post_title ?>

Any help would be greatly appreciated. This will be a great learning lesson for me so I can replicate this in the future, so again any help would be amazing.


<?php

    if (strlen($post->post_title) > 8)
       echo substr($post->post_title, 0, 8) . ' ...';
    else
       echo $post->post_title;

?>

Alternatively, if You have the mbstring extension is enabled, there's also a shorter way as suggested by Gordon's answer. If the post's encoding is multibyte, You'd need to use mbstring anyway, otherwise characters are counted incorrectly.

echo mb_strimwidth($post->title, 0, 8, ' ...');


You can use mb_strimwidth

echo mb_strimwidth('Your Title', 0, 8, '…');

If you want to truncate with respect to word boundaries, see

  • Truncate a multibyte String to n chars


You should do this in plugin because if you change the theme the changes will be lost


you can try this.

$maxlength = 8;
if (strlen($post->post_title) > $maxlength)
       echo substr($post->post_title, 0, $maxlength) . ' ...';
    else
       echo $post->post_title;

So by now you no need to change max char in all the line of code.

Thanks.

0

精彩评论

暂无评论...
验证码 换一张
取 消