How to limit the max number of characteres in the title that are displayed

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?

Related posts

Leave a Reply

3 comments

  1. 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.

  2. 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.

    <?php
    //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 } ?>
    </h1>
    
  3. 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 ). " &hellip;";
        } else {
            return $title;
        }
    }
    

    Then you can hook like this:

    add_filter( 'the_title', 'max_title_length');