Created
July 1, 2014 18:05
-
-
Save wpscholar/f3fa6fb21125e5463a15 to your computer and use it in GitHub Desktop.
Load custom page templates from within a plugin
This file contains hidden or 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 | |
/** | |
* Class Custom_Page_Templates | |
*/ | |
class Custom_Page_Templates { | |
/** | |
* Storage for all custom template paths | |
* | |
* @var array | |
*/ | |
protected static $_paths = array(); | |
/** | |
* Add actions and filters | |
*/ | |
public static function initialize() { | |
add_action( 'load-post.php', array( __CLASS__, 'register_templates' ) ); | |
add_filter( 'template_include', array( __CLASS__, 'load_template' ) ); | |
} | |
/** | |
* Register a custom template path | |
* | |
* @param string $path | |
*/ | |
public static function register_path( $path ) { | |
self::$_paths[] = $path; | |
} | |
/** | |
* Register custom templates | |
*/ | |
public static function register_templates() { | |
$theme = wp_get_theme(); | |
$templates = array_merge( $theme->get_page_templates(), self::get_custom_templates() ); | |
$cache_hash = md5( $theme->get_theme_root() . '/' . $theme->get_stylesheet() ); | |
wp_cache_set( "page_templates-{$cache_hash}", $templates, 'themes', 1800 ); | |
} | |
/** | |
* Handle loading of custom template | |
* | |
* @param string $template | |
* @return string $template | |
*/ | |
public static function load_template( $template ) { | |
$custom_template = get_post_meta( get_the_ID(), '_wp_page_template', true ); | |
if ( ! empty( $custom_template ) && array_key_exists( $custom_template, self::get_custom_templates() ) ) { | |
$template = $custom_template; | |
} | |
return $template; | |
} | |
/** | |
* Get custom templates | |
* | |
* @return array $templates | |
*/ | |
public static function get_custom_templates() { | |
static $templates = array(); | |
if ( empty( $templates ) && ! empty( self::$_paths ) ) { | |
foreach ( self::$_paths as $path ) { | |
$directory = new \RecursiveDirectoryIterator( $path ); | |
$iterator = new \RecursiveIteratorIterator( $directory ); | |
$regex = new \RegexIterator( $iterator, '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH ); | |
foreach ( $regex as $file => $matches ) { | |
$file_data = get_file_data( $file, array( 'name' => 'Template Name' ), 'page-templates' ); | |
if ( ! empty( $file_data['name'] ) ) { | |
$templates[$file] = $file_data['name']; | |
} | |
} | |
} | |
} | |
return $templates; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage: