Hack: Alter Post Title Tag Depending On the Category

So yesterday I showed you how to change the post title, as in the H1 tag of the post page, based on the category of the post. That doesn’t change the title tag, however. Users don’t see or pay attention to the title tag as much, especially with browser tabs only offering limited space for them. But search engines see these and use them in search results.

Changing the title tag is trickier. You can’t just intercept it and replace it like with the H1 tag. The document_title_parts hook gets you there, but you have an object to deal with instead of a string. This object has a few parts. Here’s a function that changes the title portion of that to prepend something if the category matches.

add_filter('document_title_parts', 'wpfilter_title_tag');
function wpfilter_title_tag($title_parts) {
	if (is_single()) {
		if (has_category('special',get_the_ID())) {
			$title_parts['title'] = 'Special: '.$title_parts['title'];
	return $title_parts;

In this case we only need to look for is_single as that is the only place where this applies — when the post is being displayed on its own page. Then we replace just the title property of the object.

You can use has_tag here as well. You can grow the if statement with more else if parts to cover other categories, tags, or combinations thereof, leaving other cases untouched.

Leave a Reply

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