How can I add an option to the Page Template list from a Plugin?

Filters? Anyone?

There’s no filter there to help: page_template_dropdown($template); is used to build the drop down and it’s not filterable.

Sneaking into the Templates Array?

To build the drop downs contents, the core meta box uses get_page_templates(). From inside, the function looks like the following:

$themes = get_themes();
$theme = get_current_theme();
$templates = $themes[$theme]['Template Files'];

But when looking into get_themes(); then there seams to be no possibility to intercept the list of templates. Further more we have the problem, that there’s no chance to get a template from outside the themes directory…

…Faking a Theme!

The theory and it’s drawbacks…

You can use register_theme_directory() to add an additional theme directory where you can place templates. So the easiest thing would be to register your plugin as themes folder too:

// Register during init hook:
register_theme_directory( plugin_dir_path( __FILE__ ).'templates' );

Note: This is where I’m not sure if it will work.

During plugin activation:
Then you should place a style.css.php file inside your templates folder. This would allow you to add variables to your file. This variable would then be the parent theme. And the parent theme should simply be the currently active theme. Then update your active theme to your plugin.

Drawback #2: About the »Appearance« UI… Maybe add a note that this “Theme” is not meant to be used as actual Theme. I leave the rest of »Avoid activating this theme« stuff up to your imagination. Anyway: It should work.

Drawback #2: This trick will successfully avoid child themes. You’re allowed to have one parent theme. Nothing more.

Leave a Comment