Add title tag automatically in WordPress

Basic implementation

On functions.php:

add_theme_support( 'title-tag' );

<head> must not have any <title> tag declared.

Backwards compatibility

In case WordPress version is less than 4.1:

if ( ! function_exists( '_wp_render_title_tag' ) ) {
	function theme_slug_render_title() {
?>
<title><?php wp_title( '|', true, 'right' ); ?></title>
<?php
	}
	add_action( 'wp_head', 'theme_slug_render_title' );
}

Custom queries

Custom queries depends on type of query, so title may be rendered in a wrong way.

add_filter( 'document_title_parts', 'change_title_part', 10 );

function change_title_part( $title ) {
	if ( get_query_var( 'favorites' ) ) {
		$title['title'] = 'Favorites';
	}
	return $title;
}

Sources

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s