It almost work correctly, but alwas return the same menu name: On home all menu elements name home on contact all menu elements name contact
function max_title_length( $title ) {
global $post;
$id = ($post->ID);
$title = get_post( $id )->post_title;
$max = 20;
if( strlen( $title ) > $max ) {
return substr( $title, 0, $max ). " …";
}
else {
return $title;
}
}
add_filter( 'the_title', 'max_title_length');
It almost work correctly, but alwas return the same menu name: On home all menu elements name home on contact all menu elements name contact
function max_title_length( $title ) {
global $post;
$id = ($post->ID);
$title = get_post( $id )->post_title;
$max = 20;
if( strlen( $title ) > $max ) {
return substr( $title, 0, $max ). " …";
}
else {
return $title;
}
}
add_filter( 'the_title', 'max_title_length');
Share
Improve this question
edited Jul 25, 2019 at 14:05
Jacob Peattie
44.2k10 gold badges50 silver badges64 bronze badges
asked Jul 25, 2019 at 13:58
nctincti
135 bronze badges
3 Answers
Reset to default 1It's because you're not using the filter correctly. The the_title
filter passes the title to be filtered as the $title
argument, but you're overwriting it with this code:
global $post;
$id = ($post->ID);
$title = get_post( $id )->post_title;
That code's completely unnecessary because the title is already available in your function:
function max_title_length( $title ) {
So simply remove those lines to filter the correct title:
function max_title_length( $title ) {
$max = 20;
if ( strlen( $title ) > $max ) {
return substr( $title, 0, $max ) . ' …';
} else {
return $title;
}
}
add_filter( 'the_title', 'max_title_length' );
Just be aware that — as you've experienced — the the_title
filter applies to all titles, including posts, pages, and menu items. So if you only want your code to apply to titles output within The Loop, you can use the in_the_loop()
function:
function max_title_length( $title ) {
$max = 20;
if ( in_the_loop() && strlen( $title ) > $max ) {
return substr( $title, 0, $max ) . ' …';
} else {
return $title;
}
}
add_filter( 'the_title', 'max_title_length' );
function max_title_length($title) {
if(is_front_page()){
$max = 8;
}
elseif(is_single()){
$max = 5;
}
else{
$max = 15;
}
if (strlen( $title ) > $max ) {
return substr( $title, 0, $max ) . ' …';
} else {
return $title;
}
}
add_filter( 'the_title', 'max_title_length' );
it still cut the menu title. in_the_loop() function not working.
function max_title_length( $title ) {
$max = 20;
if ( strlen( $title ) > $max ) {
$title = substr( $title, 0, $max ) . ' …';
}
return $title;
}
add_filter( 'the_title', 'max_title_length' );