Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
(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
add comment

2 Answers

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.

share|improve this answer
    
not to sth > 200 (which is the problem I'm facing with Thai URls), @Bainternet :) –  Eric Nguyen Mar 7 '13 at 8:28
add comment

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');
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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