Custom title tags in WordPress

How to change the meta title tag without a plugin in WordPress. It also gives an an example of adding category to the title tag for single post and page.

Custom the title tag with a filter

WordPress use get_document_title() to generate the content for the meta title tag. There are two filters to custom it. You may choose one for your purpose.

  • pre_get_document_title, this filter does not accept any parameters, it’s return value will be used as the title. If you want to completely control the title, this one will be your choice. It’s up to you to generate the title. Make sure you take care of all kinds of pages, like home, single post or page, 404, etc.
  • document_title_parts, an array of parts of the title has been generated, like “title”(page title) and “site”(site name). This filter can be used to further custom each part. Finally, each part in the array return by the filter will be joined together with a separator to form a complete title in get_document_title(). If you don’t need deep customization, this one will meet your needs.

What you do is simply define a filter of your chose, and put them in functions.php of your theme.

Change the title

function my_meta_title() {
    return 'My page title';
}
add_filter( 'pre_get_document_title', 'my_meta_title' );

Change the title parts

function change_title_part( $title ) {
    if ( array_key_exists(  $title ) ) {
        $title['title'] = "[$title['title']]"; // wrap title in "[]"
    }

    return $title;
}
add_filter( 'document_title_parts', 'change_title_part' );

Change separator in the title

You can also change the default separator in the title. Use document_title_separator filter to do it.

function change_title_separator( $separator ) {
    return '|';
}
add_filter( 'document_title_separator', 'change_title_separator' );

Example: Add category to the title tag

Below example adds category in the meta title tag for single post and page.

Add below code to your theme’s functions.php file

function add_category_to_meta_title( $title ) {
    if ( is_singular() ) {
        $new_title = array();

        if ( array_key_exists( 'title', $title ) ) {
            $new_title['title'] = $title['title'];
            unset( $title['title'] );
        }

        // add category
        $categories = get_the_category();
        if ( ! empty( $categories ) ) {
            $new_title['category'] = esc_html( $categories[0]->name );  
        }

        foreach( $title as $k => $v) {
            $new_title[$k] = $v;
        }

        return $new_title;
    }

    return $title;
}
add_filter( 'document_title_parts', 'add_category_to_meta_title' );

If you are using an SEO plugin, like Yoast, the above code may do not work for code conflictions. To solve that, define pre_get_document_title filter, so the above code will take effect.

function cust_document_title() {
    return '';
}
add_filter( 'pre_get_document_title', 'cust_document_title', 99 );