Skip to content

Instantly share code, notes, and snippets.

@jimboobrien
Forked from wpscholar/custom-page-templates.php
Created September 20, 2017 23:15
Show Gist options
  • Save jimboobrien/9ad7cca78a5fc2d0260efb64a4e121a8 to your computer and use it in GitHub Desktop.
Save jimboobrien/9ad7cca78a5fc2d0260efb64a4e121a8 to your computer and use it in GitHub Desktop.
Load custom page templates from within a plugin
<?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