Can’t change the title tag with wp_title filter

I’m using a theme child of Ultra Theme. This theme is using this :

add_theme_support( 'title-tag' );

I’d like to customize the title tag of all posts & pages, here is my code :

add_filter( 'wp_title', 'my_custom_title', 10, 2);
function my_custom_title() {
    return("Foo bar");
}

The code is not working and I can’t figure out why !

2 Answers
2

When adding title-tag support in a theme, the title tag can be filtered by several filters, but not wp_title. The reason is that if the theme supports title-tag, WordPress uses wp_get_document_title() instead of wp_title().

For themes with support for title-tag you can use document_title_parts:

add_filter( 'document_title_parts', 'filter_document_title_parts' );
function filter_document_title_parts( $title_parts ) {

    $title_parts['title'] = 'The title'; 
    $title_parts['tagline'] = 'A tagline';
    $title_parts['site'] = 'My Site';

    return $title_parts; 

}

Or pre_get_document_title:

add_filter( 'pre_get_document_title', 'filter_document_title' );
function filter_document_title( $title ) {

    $title="The title"; 

    return $title; 

}

Leave a Comment