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

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:

Read More

<?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.

Related posts

Leave a Reply

4 comments

  1. <?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, ' ...');
    
  2. 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.