Create custom page templates with plugins?

Is it possible to make custom page templates available from a plugin?

get_page_template() can be overridden via the page_template filter. If your plugin is a directory with the templates as files in them, it’s just a matter of passing the names of these files. If you want to create them “on the fly” (edit them in the admin area and save them in the database?), you might want to write them to a cache directory and refer to them, or hook into template_redirect and do some crazy eval() stuff.

A simple example for a plugin that “redirects” to a file in the same plugin directory if a certain criterium is true:

add_filter( 'page_template', 'wpa3396_page_template' );
function wpa3396_page_template( $page_template )
{
    if ( is_page( 'my-custom-page-slug' ) ) {
        $page_template = dirname( __FILE__ ) . '/custom-page-template.php';
    }
    return $page_template;
}

Leave a Comment