the_title() filter is also applied in menu title

I use following code to change the title of WordPress posts and pages. But it does change nav menu item titles too which I want to avoid.

I want to change the title of posts and pages, in home page, all archive pages and all widgets(recent posts widget, random post widget, etc)

There are similar questions in both Stack Overflow and WP Stack Exchange suggesting to use in_the_loop() function. Unfortunately it is not works for me because if I place it it affect to the sidebar widgets. That means, if I use in_the_loop() function, title filter not affect for “recent posts widget, random post widget” too.

So how can I apply the_title filter for just posts and pages types?

function pppp_title_update( $title, $id = null ) {

if ( ! is_admin() ) {
if(is_singular(array(‘post’,’page’)) || is_archive() || is_home()){
if(in_the_loop()){
$current_post_id = get_the_ID();
$new_titile = get_post_meta($current_post_id, ‘pp_new_title’,true);
return $new_titile;
}
}
}

return $title;
}
add_filter( ‘the_title’, ‘pppp_title_update’, 10, 2 );

Read more here:: the_title() filter is also applied in menu title

Leave a Reply

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