How to Truncate WordPress Post Titles with PHP

While working on our client’s site, the design’s width would not allow us to keep the long titles to be displayed on the homepage. After searching the web for options, we came across several plugins that would truncate WordPress titles, but they would do it sitewide whereas we only wanted it on the homepage. In this article, we will share with you how you can truncate WordPress Post Titles with PHP.

First open your index.php or the file location where you want to truncate the title. Then paste the following code to replace your the_title tag.

1
2
3
4
5
6
7
8
9
<a href="<?php the_permalink() ?>">
<?php
$thetitle = $post->post_title; /* or you can use get_the_title() */
$getlength = strlen($thetitle);
$thelength = 25;
echo substr($thetitle, 0, $thelength);
if ($getlength > $thelength) echo "...";
?>
</a>

Make sure you edit the $thelength variable from 25 to the character count of your need. You would have to estimate the count for your theme design. The code adds the length variable and then use the conditional tag to see if the title length matches our desired length. If it is longer, then the code adds ‘…’ in front. Most of the time, you will use this only on specific areas where the width is fixed in the theme.

*This is a good code to have as a theme designer*.

Source: Codezroz

Leave a Reply

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

error: Content is protected !!

Pin It on Pinterest

Add address