Method 1: Truncate WordPress Post Titles With a WordPress Function
The easiest way to truncate WordPress post titles is by adding a custom function. Follow these steps:
Step 1: Install and Activate WPCode Plugin
- Go to your WordPress dashboard.
- Navigate to Plugins » Add New.
- Search for WPCode and click Install Now, then Activate.
Step 2: Add Custom Code Using WPCode
- In your WordPress dashboard, go to Code Snippets » + Add Snippet.
- Hover over Add Your Custom Code (New Snippet) and click the Use snippet button.
Step 3: Add the Truncate Function
- Copy the following code:
php
function max_title_length( $title ) {
$max = 35;
if( strlen( $title ) > $max ) {
return substr( $title, 0, $max ) . " …";
} else {
return $title;
}
}
add_filter( 'the_title', 'max_title_length');
- Paste the code into the Code Preview pane in WPCode.
Step 4: Configure and Save the Snippet
- Choose PHP Snippet from the Code Type drop-down menu.
- Toggle the Active setting on.
- Click the Save Snippet button.
Your blog post titles will now be truncated to 35 characters. To change the length, adjust the $max
variable in the code.
Method 2: Truncate WordPress Post Titles by Changing Theme Files
This method provides more control over where your titles are truncated. Follow these steps to modify your theme files:
Step 1: Edit Your Theme Files
- Access your WordPress files using an FTP client or your hosting file manager.
- Navigate to your theme directory (usually found in
/wp-content/themes/your-theme-name/
). - Open the file where you want to truncate titles, such as
index.php
,archive.php
, orsingle.php
.
Step 2: Add the Truncate Code
- Find the line with
<?php the_title(); ?>
within the loop. - Replace it with the following code:
php
<a href="<?php the_permalink(); ?>">
<?php
$thetitle = get_the_title();
$thelength = 25;
echo substr( $thetitle, 0, $thelength );
if ( strlen( $thetitle ) > $thelength ) echo "…";
?>
</a>
- Save the file and upload it back to your theme directory if you’re using FTP.
Step 3: Customize Title Length
To change the character limit, modify the $thelength
variable in the code to your preferred length.
By following these methods, you can control the length of your post titles, ensuring they fit well within your site’s design and layout.