How do I show ‘…’ when the WordPress title exceeds length

I have a function which trims the title to a certain length. It does trim the title properly, but always shows ‘…’ even if the title doesn’t exceed the length.

Does anyone know how to make it so the ‘…’ will only show if the title is too long?

Read More
// Title Excerpt//
function the_titlesmall($before = '', $after = '', $echo = true, $length = false) { $title = get_the_title();

    if ( $length && is_numeric($length) ) {
        $title = substr( $title, 0, $length );
    }

    if ( strlen($title)> 0 ) {
        $title = apply_filters('the_titlesmall', $before . $title . $after, $before, $after);
        if ( $echo )
            echo $title;
        else
            return $title;
    }
}
//End Title Excerpt

PHP in loop

<?php the_titlesmall('', '', true, '15') ?>

Related posts

Leave a Reply

2 comments

  1. EDIT: Focusing on trimming the title.

    Try adding this function to your functions.php.

    function short_title($after = '', $length) {
        $mytitle = get_the_title();
        if ( strlen($mytitle) > $length ) {
        $mytitle = substr($mytitle,0,$length);
        echo $mytitle . $after;
        } else {
        echo $mytitle;
        }
    }
    

    Then, wherever you want the title to appear put the following: <?php short_title('...', 40); ?> That would limit it to 40 characters, and add an … if it exceeds it.

  2. If you can’t trim it at display time using CSS’s text-overflow: ellipsis, I’d probably just use mb_strimwidth. It’s what it’s designed for. For basic use, something like this, perhaps:

    <?php echo mb_strimwidth(get_the_title(), 0, 20, '...'); ?>
    

    …and roll it into your own function as necessary.