admin管理员组

文章数量:1195309

I've created a plugin and I am trying to include an post template that the user can optionally use.

I've tried the following,

add_filter( 'template_include', 'insert_my_template' );

function insert_my_template( $template )
{
if ( 'events' === get_post_type() )
    return plugin_dir_path( __FILE__ ) . 'templates/single-events.php';

return $template;
}

However this only seems to completely override the template, it does not allow the user to select a different template for use. How can I achieve a similar result to when adding the template into the theme folder while keeping it all in the plugin? (Where the user can choose which template to be displayed) Like this:

I've created a plugin and I am trying to include an post template that the user can optionally use.

I've tried the following,

add_filter( 'template_include', 'insert_my_template' );

function insert_my_template( $template )
{
if ( 'events' === get_post_type() )
    return plugin_dir_path( __FILE__ ) . 'templates/single-events.php';

return $template;
}

However this only seems to completely override the template, it does not allow the user to select a different template for use. How can I achieve a similar result to when adding the template into the theme folder while keeping it all in the plugin? (Where the user can choose which template to be displayed) Like this:

Share Improve this question asked Jul 20, 2022 at 1:14 apockapock 132 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

Not sure if there's a better way to do it, but you can use the theme_<post type>_templates filter to add your custom template to the "Template" dropdown, and then use the template_include filter to ensure the correct file is loaded.

So something like this should work:

add_filter( 'template_include', 'my_events_template_include' );
function my_events_template_include( $template ) {
    if ( 'events' === get_post_type() ) {
        $file = plugin_dir_path( __FILE__ ) . 'templates/single-events.php';
        return ( $file === get_page_template_slug() ) ? $file : $template;
    }

    return $template;
}

add_filter( 'theme_events_templates', 'my_plugin_theme_events_templates' );
function my_plugin_theme_events_templates( $post_templates ) {
    $file = plugin_dir_path( __FILE__ ) . 'templates/single-events.php';
    $post_templates[ $file ] = __( 'Single Events', 'your-text-domain' );
    return $post_templates;
}

Note: The array key of $post_templates should be a file name/path relative to the active theme directory, but since we're using a full filesystem path, then we had to use the template_include filter to load the correct file from the plugin directory.

本文标签: Plugin custom post template without overriding all posts