I am following this tutorial — "Display Your Popular Posts In WordPress Without A Plugin" and want to limit the max number of characters in the title that are displayed. Also, why is the thumbnail, at times, smaller than the number I define in the php?

  • (1) Bainternet gave a wonderful answer, and as an alternative, you can also get the same effect using text-overflow CSS property. (2) You said you've defined the thumbnail size in php. If so, did you enable "hard cropping"? Unless you do that, dimensions of the thumbnails generated aren't going to be exact. – its_me Jun 27 '12 at 1:58

first add this function to your functions.php file

function max_title_length($title){
     $max = 20;
    return substr( $title, 0, $max ). " …";

then before the loop of the code you linked add this line to hook the above function:

add_filter( 'the_title', 'max_title_length');

and after the loop remove this filter:

remove_filter( 'the_title', 'max_title_length');

and just change $max = 20; to whatever you want.

  • not to sth > 200 (which is the problem I'm facing with Thai URls), @Bainternet :) – ericn Mar 7 '13 at 8:28

I've improved the @Bainternet answer to only display ... when the title is longer than $max:

function max_title_length( $title ) { 
        $max = 30;
    if( strlen( $title ) > $max ) {
        return substr( $title, 0, $max ). " …";
    } else {
        return $title;

Then you can hook like this:

add_filter( 'the_title', 'max_title_length');

You can use this bit to limit the number of characters displayed and append an ellipsis.

In this particular example I've set it to trunicate at 38 characters and only display the ellipsis if the title was trunicated. And regardless of the length, display the full title on the single_post page.

//assign the title to a variable
$the_title = esc_attr ( the_title_attribute ( 'echo=0' ) );
//specify our desired max character count    
$max_length = 38;
//strlen gets the length of the string
$title_length = strlen ( $the_title ); 

// check if the length of the string is greater than our assigned max length
if ( $title_length > $max_length ) {
    // if it is display a substring of the title from the 
    // first character to the 38th character and append ...
    $title_excerpt = substr ( $the_title, 0, $max_length ) . '...';
} else {
    // otherwise just return the_title()
    $title_excerpt = $the_title;
} ?>

<h1 class="entry-title">
    <?php if ( is_single () ) { // If article page
        the_title ();
    } else {  // If homepage

    <a href="<?php the_permalink (); ?>" title="<?php echo esc_attr ( the_title_attribute ( 'echo=0' ) ); ?>" rel="bookmark"><?php echo $title_excerpt; ?></a>
    <?php } ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.