How to Change SEO Page Title Dynamically in WordPress

You often are in a need of displaying your Post title dynamically, i.e. the text that appears inside <title></title> tag of the head section of the page. For example the Title of the Post itself? To get this accomplished we have to write a custom function in our theme’s functions.php file and hook this function to one of WordPress’s Filter Hook. Let’s see how.

In our functions.php we write the following function named themename_reset_page_title(). The word ‘themename’ should be replaced with the name of your theme. It is not mandatory to follow this naming convention, but always recommended so that it the chance of your function to conflict with WordPress’s inbuilt function names. so if your theme name is mytheme, then your function name should ideally be mytheme_reset_page_title.

function mytheme_reset_page_title() {
   global $post;
   $page_title = get_bloginfo( 'name' ) . ' | ' . get_the_title( $post );
   return $page_title;
}

add_filter('wp_title', 'mytheme_reset_page_title');

 

Let’s assume:
Your site title is: Development with WordPress
Your Post title is: How to Change Post Title Dynamically in WordPress

 

Save the file and run the page in browser and View Source. You should be able to see that thesection now looks like this:

<title>Development with WordPress | How to Change Post Title Dynamically in WordPress</title>

Now you need a separate page title for your site’s homepage. To achieve this we need to modify the above function body to check whether user is on your site’s home page or front page. If yes, title will display Development with WordPress | WordPress essentials, otherwise it takes Post title as above and display title like we have in the previous section.

function mytheme_reset_page_title() {
   global $post;
   if( is_home() || is_front_page() ) {
     $page_title = get_bloginfo( 'name' ) . ' | WordPress essentials';
   } else {
     $page_title = get_bloginfo( 'name' ) . ' | ' . get_the_title( $post );
   }
   return $page_title;
}

add_filter('wp_title', 'mytheme_reset_page_title');

That’s it! You can customize your page title for category page, taxonomy page, by specific post_types and more.