Skip to Content

How to Shorten Title Length in WordPress

|WordPress|0 Comments

This can be used to shorten pretty much any text in WordPress. I recently had to use it to make sure recent comment titles didn’t cause them to spill over to the next line so I’ll use it as an example…

Title Spills Over Before Shortening

Double Line Titles in WordPress
Here is the title section in my recent posts widget:

<?php echo get_the_title(); ?>

Then I replace it with this:

<?php echo onepix_shorten(get_the_title(), 42) ; ?>

 
And add this to the functions.php file. (I believe it was originally courtesy of this post).
 

//shorten string and add suffix link
function onepix_shorten($string, $length) {

    // Convert 'smart' punctuation to 'dumb' punctuation, strip the HTML tags,
    // and convert all tabs and line-break characters to single spaces.
    $short_desc = trim(str_replace(array("\r","\n", "\t"), ' ', strip_tags($string)));

    $stringlen = strlen( $short_desc );
    if($stringlen > $length){
        // By default, an ellipsis will be appended to the end of the text.
        $suffix = '?';
        // Cut the string to the requested length, and strip any extraneous spaces 
        // from the beginning and end.
        $desc = trim(substr($short_desc, 0, $length));
        // Find out what the last displayed character is in the shortened string
        $lastchar = substr($desc, -1, 1);
        // If the last character is a period, an exclamation point, or a question 
        // mark, clear out the appended text.
        // Append the text.
        $desc .= $suffix;
        // Send the new description back to the page.
        return $desc;
    } else {
        // Send the new description back to the page.
        return $short_desc;
    }

}

 

This will make a nice tidy, well formatted, single line title.

 

After Shortening… Nice and Tidy

Single Line Titles in WordPress

 

Related Posts

Share This

Related Tags

no comments yet but open for them

Post a Reply

Your email address will not be published. Required fields are marked *