WordPress Select template to render query in wordpress

Sometimes you want to use one archive template for different situations. In wordpress select a template by using the ‘template_include‘ filter. You have to use the function ‘locate_template()‘ ┬áto set the template.

This is if you want to stray from the normal way wordpress enables you to select a template. WordPress lets you create page templates in a way you can select them from a post (codex link). You can create custom archive pages for custom posts in a simular way (codex link). But what if you want to use an archive template for a page, or one template for everything…

WordPress select template

<?php

// put in your functions
function template_chooser($template)
{
  global $wp_query;
  $post_type = get_query_var('post_type');
  // If the query is a search query AND the post type is set to your_custom_post_type
  if( $wp_query->is_search && $post_type == 'your_custom_post_type' )
  {
    // use the your_custom_page.php to display the output
    return locate_template('your_custom_page.php');
  }
  // if the tax is your_tax
  if( is_tax('your_tax') ) 
  {
    // use the your_custom_page.php template to output
    return locate_template('your_custom_page.php');
  }
 
  return $template;
}
add_filter('template_include', 'template_chooser');

 

One Comment

  • Leave a Reply

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