SJL Web Design

Limit the Length of WordPress Post Titles

Recently we were working on a WordPress website with a very specific layout that meant post titles on the blog homepage could only be a certain length before they started effecting the pixel perfect layout of that page.

To conquer this we decided to adopt an old method of shortening the title tag and adding a ‘…’ to the end to indicate that this was only a part of the entire title.

From searching the web to see if anyone else had came up with a pre-existing plugin/function, I found that there weren’t any straightforward solutions or clear documentation that would offer me a ‘quick fix’. So in a moment of madness I thought it would be a nice idea to share the code I came up with to help anyone in the future with a ‘quick fix’.

The Function

Just add the following code to the functions.php file inside your WordPress theme folder (wp-content > themes > your-theme), if you can’t find a functions.php file just create one yourself and upload it to your server.


<?php
// Limit Post Title
function shortened_title() {
$original_title = get_the_title();
$title = html_entity_decode($original_title, ENT_QUOTES, "UTF-8");
// Set Limit
$limit = "55";
// Set End Text
$ending="...";
if(strlen($title) >= ($limit+3)) {
$title = substr($title, 0, $limit) . $ending; }
echo $title;
}
?>

Now all you need to do is replace the existing:


<?php the_title(); ?>

With our new shortened title function:


<?php shortened_title(); ?>

Change the limit and ending variables in the functions.php file to match your needs and there you have it, your extra long titles should now be limited to match your pixel perfect layout.

1 Response to “Limit the Length of WordPress Post Titles”

David Wheatley Says:

Cheers guys, this is a useful piece of code to stop clients disturbing the layout of a design…

Leave a Reply