1

I am trying to learn how to shorten 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.

Zach Smith
  • 5,490
  • 26
  • 84
  • 139

4 Answers4

5
<?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, ' ...');
Community
  • 1
  • 1
Saul
  • 17,973
  • 8
  • 64
  • 88
  • this looks so, beautiful and elegant. ty so much <3 – Zach Smith Dec 14 '10 at 11:42
  • @HollerTrain: Initially the argument order of `substr()` was not correct in my answer. It's fixed now. – Saul Dec 14 '10 at 11:48
  • using `mb_strimwidth` has the additional benefit that it will yield correct results for multibyte characters like these âãäåæçèéêë. Also note that I've used an actual ellipsis `…` instead of three dots `...`. – Gordon Dec 14 '10 at 12:04
1

You can use mb_strimwidth

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

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

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
0

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

mazgalici
  • 608
  • 6
  • 10
0

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.

Chandresh M
  • 3,808
  • 1
  • 24
  • 48