Last active
October 16, 2016 08:23
-
-
Save akumaf/3564f2bff70d85dca6fed39130c3994c to your computer and use it in GitHub Desktop.
See http://arevico.com/change-the-template-for-all-posts-in-a-specific-category/ on how to use this gist.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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