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 badges1 Answer
Reset to default 2Not 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
版权声明:本文标题:Plugin custom post template; without overriding all posts 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738496422a2090012.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论