Site logo

Archived topic

Number of characters in post title

7 replies · Started by Roger on July 15, 2021

Viewing posts 1–8 of 8

Hi,

I'm using this code to limit the number of characters in the post title. It's working on both the archive page and the single post page.

How to limit the number of characters on archive page only?

This code is in function.php

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

This code is in archive.php
add_filter( 'the_title', 'max_title_length');

Hi there,

in your function, change this line:

if( strlen( $title ) > $max ) {

to:

if( is_archive() && strlen( $title ) > $max ) {

Great!

Thank you!

You're welcome

Hello!

I tried adding the things mentioned above, but it doesn't work for me. I have a child theme and want to limit characters on archive pages.

functions.php code:

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

arhive.php code:

add_filter( 'the_title', 'max_title_length');

Can you tell me what's wrong?

Thanks!

Hi there,

this code:

add_filter( 'the_title', 'max_title_length');

Remove that from the archive.php and it into your functions.php, before or after the other code will do.

Hello!

Still doesn't work.

Looks like this now:

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

add_filter( 'the_title', 'max_title_length');

Here's the archive page.

I've also tried placing the code above the first one.

Try this snippet instead:

add_filter( 'the_title', function( $title ){
    $max  = 20;
    if ( !is_archive() || !is_home() || $max > strlen( $title ) ) {
        return $title;
    }
    return substr( $title, 0, $max ) . "…";
}, 10, 2 );

Note - the_title function in WordPress is used in lots of places from menus to widgets. So this may affect other elements on the page.

This archived topic is closed to new replies.