Category:

One way to automatically truncate (or limit the length of) blog post titles is to add the following PHP code to your theme’s functions.php file. This is the same code that many people recommend, but I added two small details. If you hover over the title, the full post title shows in the browser’s default tooltip. Also, this will only truncate the title on your home page and in archives. This is because most likely you want the full title on single pages. But, if not, just add the following after “is_archive”: || is_single().

function max_title_length( $title ) {
    // Check if it's the home page or archive page and within the main content loop
    if ( ( is_home() || is_archive() ) && in_the_loop() ) {
        $max = 35;
        if( strlen( $title ) > $max ) {
            // Add a "title" attribute with the full title
            $title = '<span title="' . esc_attr( $title ) . '">' . substr( $title, 0, $max ) . '…</span>';
        } else {
            $title = esc_html( $title );
        }
    }

    return $title;
}

add_filter( 'the_title', 'max_title_length', 999 );

I experienced an odd conflict with a certain theme that has a very fancy menu. I never would have thought that this function would conflict with a menu. But, it did. So, I added the part near the beginning that says, “&& in_the_loop().” In other words, only mess with titles in the loop (where posts are).



Leave a Reply

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

Billy Wilcosky