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?
// 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') ?>
EDIT: Focusing on trimming the title.
Try adding this function to your
functions.php
.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.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:…and roll it into your own function as necessary.