Plugin custom post template; without overriding all posts

Question

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.

0
WP_Alpaca 4 months 2022-07-19T20:14:21-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse