Skip to content

Instantly share code, notes, and snippets.

@akumaf
Last active October 16, 2016 08:23
Show Gist options
  • Save akumaf/3564f2bff70d85dca6fed39130c3994c to your computer and use it in GitHub Desktop.
Save akumaf/3564f2bff70d85dca6fed39130c3994c to your computer and use it in GitHub Desktop.
<?php
/**
* This code is intended for both theme developers and webmasters. It allows you to specify a page template
* for any post belonging to a specific category.
*
* The script looks for a file called in-category-{$slug} and if it exists and uses that file as a template. Replace {$slug] with
* the friendly name of the category (slug)
*
* @author H.F. Kluitenberg < http://arevico.com/ >
* @usage See http://arevico.com/change-the-template-for-all-posts-in-a-specific-category/
*/
$inCat = new InCat();
class InCat
{
/**
* Check if the current post belongs to a specific category if a template has been found return it.
*
* @param string $template The full location to the template
*/
private function inCategoryTemplate( $template ){
global $wp_query;
$availableTemplates = wp_get_theme()->get_page_templates();
if (!$wp_query->is_singular)
return $template;
$catNames = array();
$cats = get_the_category();
if (empty($cats))
return $template;
foreach( $cats as $cat)
$catNames[] = preg_quote($cat->slug);
foreach ($availableTemplates as $path => $name )
if (preg_match('/in\-category\-()' . implode('|', $catNames) . '/', $path))
return get_template_directory(). '/' . $path;
return $template;
}
/**
* Constructor. Adds all required hooks and filters
*/
function __construct()
{
add_filter( 'template_include' , array($this, 'inCategoryTemplate'), 99 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment