Farooq Ahmad Farooq Ahmad - 4 months ago 9
PHP Question

Create single.php for specific tag by tag id or name

i have multiple tags and want to create multiple single.php for everyone tag.

How create single.php for tags??


This code working well for category, how to edit it for tags??


function my_category_templates($single_template) {
global $post;

if ( in_category( 'raspee' )) {
$single_template = dirname( __FILE__ ) . '/single-raspee.php';
}
return $single_template;
}
add_filter( "single_template", "my_category_templates" );

Answer

You can check for tag with has_tag() function...

if ( has_tag( 'awesome' )) {
    $single_template = dirname( __FILE__ ) . '/single-awesome.php';
}

You entire code will look like this...

function my_category_templates($single_template) {
global $post;

  if ( in_category( 'raspee' )) {
    $single_template = dirname( __FILE__ ) . '/single-raspee.php';
  } else if ( has_tag( 'awesome' )) {
    $single_template = dirname( __FILE__ ) . '/single-awesome.php';
  }
  return $single_template;
}
 add_filter( "single_template", "my_category_templates" );

We added else if to test for tag it only if first condition is not met, feel free to use if again if you have to...
Hope that helps.