I've been looking around for the past couple hours for a way to create a custom page template from within a plugin but haven't had any luck yet.
What I am specifically trying to do is add an option to the list of available page templates when editing a page, and not using some other method like if( is_page( 'page-slug' ) ) { /* etc */ }
Is there a global variable I can modify to do this?
Edit:
I'm using this code currently, based on the link @m0r7if3r gave me in a comment, the problem is it will run this function when viewing the page, but not when editing the page (to populate the dropdown list with the page templates):
class JW_SiteGrader {
private static $instance;
private function __construct() {
add_action( 'template_redirect', array( &$this, 'sitegrader_template_redirect' ), 20 );
}
public static function getInstance() {
// Return the class data in a Singleton fashion
if (self::$instance == null)
self::$instance = new JW_SiteGrader();
return self::$instance;
}
public function sitegrader_template_redirect() {
add_filter( 'page_template', array( &$this, 'sitegrader_page_template' ), 10, 1 );
}
public function locate_plugin_template( $template_names, $load = false, $require_once = true ) {
if ( !is_array( $template_names ) )
return '';
$located = '';
$this_plugin_dir = WP_PLUGIN_DIR . '/' . str_replace( basename( __FILE__ ), '', plugin_basename( __FILE__ ) );
foreach ( $template_names as $template_name ) {
if ( !$template_name )
continue;
if ( file_exists( STYLESHEETPATH . '/' . $template_name ) ) {
$located = STYLESHEETPATH . '/' . $template_name;
break;
} else if ( file_exists( TEMPLATEPATH . '/' . $template_name ) ) {
$located = TEMPLATEPATH . '/' . $template_name;
break;
} else if ( file_exists( $this_plugin_dir . $template_name ) ) {
$located = $this_plugin_dir . $template_name;
break;
}
}
if ( $load && '' != $located )
load_template( $located, $require_once );
return $located;
}
public function sitegrader_page_template( $template ) {
$object = get_queried_object();
if ( 'page' == $object->post_type ) {
// New
$templates[] = "page-sitegrader.php";
// Like in core
$templates[] = "page-{$object->post_type}.php";
$templates[] = "page.php";
return locate_template( $templates );
}
// return apply_filters('page_template', $template);
return $template;
}
}
Edit 2:
It seems that this functionality will be released in a future update, I read quite a few trac tickets about this and there has been some discussion but no real answer (hoping for 3.4). Will list trac tickets URLs here in a bit.
Edit 3:
The code above works, BUT, the only issue I'm having at this point is there's no template being added to the dropdown list when editing/adding a new page. I'm trying a few things and will update my question soon.
page_template
hook, the code above in my edit is what's currently being used. Do I need to use thetemplate_redirect
hook and then add thepage_template
filter in there?