Hack: Alter Post Titles Depending On the Category

The H1 title tag of your post may not be idea for SEO. A title may work better if you could append or prepend special text depending on the category. For instance, if you review bars and restaurants, you may want to prepend Bar or Restaurant to the title, which is usually just the name of the establishment.

Here is some code to do just that. It doesn’t just take the category name and stick it in front though. You may only want to do this for some categories. And the actual category name may not be the idea text either. For instance, you may want to use “Bars and Pubs” instead of just “bar” as the text. So in this code you add to the if statement for each category you want to treat in this special way and the prepended text can differ from the name of the category. You could even test for multiple categories and use special text for that too.

add_filter('the_title', 'wpfilter_title', 10, 2);
function wpfilter_title($title,$id=null) {
	if (is_single() || is_front_page() || is_category()) {
		if (has_category('special',$id)) {
			$title = 'Special: '.$title;
			return $title;
		}
	}
	
	return $title;
}

Add this to your functions.php or custom plugin and just edit it as needed. You could use has_tag as well. Note that the tests is_single, is_front_page and is_category make sure the title change isn’t seen elsewhere, like in your admin post list. You’ll see the real titles there.

Leave a Reply

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