How to conditionally add meta tag for specific page template?

Sometimes you may want to load some meta tags only on specific page template. While there are plugins available to do this, if you keep adding plugin for each and every trivial requirement you end up having so many plugins over the period of time. You can simply add the code in your theme’s functions.php file based on any of the following scenario:

Let’s say you want to add a meta tag on about page that has custom page template. Then you can use a code like below:

function mytheme_add_meta_tags() {
// Assuming you want to add meta tag on about page template
   if ( is_page_template( 'about.php' ) ) {
      // Change this to meta tag you want to add
      echo '<meta name="meta_name" content="meta_value" />';
   }
}
add_action('wp_head', 'mytheme_add_meta_tags');

If your template resides in a directory then you will need to do something like below:

function mytheme_add_meta_tags( ){
if ( is_page_template( 'directory-name/page-about.php' ) ) {
   // Change this to meta tag you want to add
   echo '<meta name="meta_name" content="meta_value" />';
  }
}
add_action('wp_head', 'mytheme_add_meta_tags');

In case you want to check for more than one custom page template and load the meta tag then you can do something like below:

function mytheme_add_meta_tags( ){
    if ( is_page_template( array( 'template-full-width.php', 'template-product-offers.php' ) ) ) {
      // Change this to meta tag you want to add
      echo '<meta name="meta_name" content="meta_value" />';
    }
}
add_action('wp_head', 'mytheme_add_meta_tags');

Sometime you may want to load the meta tag on a template from WordPress template hierarchy and not the custom page template. For example this is how you will do it to load the meta tag on archive page using conditional tag:

function mytheme_add_meta_tags( ){
/* check if its an archive page - category, tag, other taxonomy term, custom post type archive, 
author and date-based pages are all types of archives */
    if ( is_archive() ) {
      // Change this to meta tag you want to add
      echo '<meta name="meta_name" content="meta_value" />';
    }
}
add_action('wp_head', 'mytheme_add_meta_tags');

Do let us know if this was helpful or not using the comments section below.

Leave a Reply