Last active
October 16, 2016 08:24
-
-
Save akumaf/5dec39f90d65dae52b506bebdf0b5ce2 to your computer and use it in GitHub Desktop.
See http://arevico.com/templates-for-custom-post-types-and-posts/ 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 | |
/** | |
* Fast and Efficient Way to Include Template abilities for posts and custom post types | |
* | |
* Author H.F. Kluitenberg < Arevico.com > | |
* How to use: | |
* See: http://arevico.com/templates-for-custom-post-types-and-posts/ | |
*/ | |
class ArevicoTheme | |
{ | |
/** | |
* Add all hooks and filters | |
*/ | |
function __construct(){ | |
add_filter( 'template_include' , array($this, 'metaTemplate'), 99 ); | |
} | |
/** | |
* Switch the template when a meta tag (custom field) has been defined | |
* | |
* @param string $template The full path to the template file | |
* @return string the full path to the template file to be used | |
*/ | |
private function metaTemplate( $template ){ | |
global $wp_query; | |
// Only on pages and posts | |
if (! (is_page() || (is_singular() ) )) | |
return $template; | |
// Get a list of all registered templates in the form | |
// { relative location } => { Template Name } | |
$availableTemplates = wp_get_theme()->get_page_templates(); | |
$metaTemplate = get_post_meta( get_the_ID(), 'template', true); | |
// If we didn't specify a template, just return the current template | |
if (!$metaTemplate) | |
return $template; | |
// The template supplied is the php file | |
if ( stripos($metaTemplate,'.php') !== false) | |
return get_template_directory(). '/' . $metaTemplate; | |
foreach ($availableTemplates as $path => $name) { | |
if (strcasecmp($name, $metaTemplate) === 0 ) | |
return get_template_directory(). '/' . $path; | |
} | |
// else a template name has been supplied | |
return $template; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment