- This topic has 7 replies, 3 voices, and was last updated 3 years, 11 months ago by
David.
-
AuthorPosts
-
July 15, 2021 at 6:41 am #1856698
Roger
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');July 15, 2021 at 7:15 am #1856756David
StaffCustomer SupportHi there,
in your function, change this line:
if( strlen( $title ) > $max ) {to:
if( is_archive() && strlen( $title ) > $max ) {July 15, 2021 at 7:32 am #1856781Roger
Great!
Thank you!
July 15, 2021 at 8:57 am #1857037David
StaffCustomer SupportYou’re welcome
July 14, 2022 at 2:29 am #2282354Filip
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!
July 14, 2022 at 2:58 am #2282378David
StaffCustomer SupportHi 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.
July 14, 2022 at 3:04 am #2282382Filip
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.
July 14, 2022 at 3:54 am #2282419David
StaffCustomer SupportTry 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_titlefunction in WordPress is used in lots of places from menus to widgets. So this may affect other elements on the page. -
AuthorPosts
- You must be logged in to reply to this topic.