Wordpress - 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.


As a suggestion for a potential work around have you considered using the WordPress file system to write a page template file from your plugin to your current active theme directory? Depending upon how much control you want over this process you can have your plugin write the file on activation and remove it on uninstall. Alternatively you could could create page template files dynamically from within your plugin UI using a form to pass certain values such as the page template name which is to appear in the dropdown box of the post edit screen. You could also in theory remove the page template from within your plugin UI at the click of a button and similarly add multiple templates for different purposes. There's a good post on using the file system over at Otto's blog. I don't have the link with me now but you can search for it.

I hope they release what you were intending to do by way of a hook in the next core release.