Categories
WordPress

Modify Title Tag: Post Heading + Category

In this tutorial, you’ll learn how to modify the Title tag for Wordpress posts. We’ll use document_title_parts filter hook to modify the Title tag. For example, you’ve created a post and assigned it a category Wordpress. For SEO purposes, you want this category to appear in the post title. By following this tutorial you can add single or multiple categories (if assigned) in the page title automatically.

From the Dashboard, click Appearance and choose Theme Editor. It will open the Edit Themes page:

Your active theme will automatically selected and appears in Select theme to edit drop-down menu. Click Themes Functions (functions.php) from the Themes Files section to open it in the editor:

Next, insert the following code in functions.php file (which we’ve already opened in the editor, see above image). The following code modifies the Title tag by adding the Category name after the post title:

add_filter('document_title_parts','include_category_in_title');
function include_category_in_title($array){
 $categories = get_the_category();

 if (empty($categories) or !is_single())
  return $array;

 $array['title'] .= ' in '. $categories[0]->name;
 return $array;
}

The above code outputs the following result when you open a post in a browser. The code adds single category name in the post title even you’ve assigned more than one categories to the post:

Before:
<title>My First Post – MyBlog</title>

After:
<title>My First Post in WordPress – MyBlog</title>

Example 2: Include all categories in post title

add_filter('document_title_parts','include_category_in_title');
function include_category_in_title($array){
 $categories = get_the_category();

 if (empty($categories) or !is_single())
  return $array;

 $j = $array['title'] .' in ';

 foreach ( $categories as $cat ) {
  $j .= $cat->name.' ';
 }

 $array['title'] = $j;
 return $array;
}

For example, if you’ve assigned two categories, WordPress and PHP, to a post, the above code adds all categories at the end of post title:

Before:
<title>My First Post – MyBlog</title>

After:
<title>My First Post in WordPress PHP – MyBlog</title>