通过插件添加自定义帖子类型模板

fri*_*ice 3 wordpress post

我正在为自定义帖子类型创建一个插件。我想为其添加一个自定义模板。但我不确定如何通过插件添加它。

如何通过插件添加自定义帖子类型模板?

请帮忙!

小智 5

您只需在自定义插件中为自定义帖子类型创建和分配自定义页面模板即可。

只需在插件目录的新模板子目录中创建 2 个模板文件 - single-{post_type}.phparchive-{post_type}.php 。

然后在主插件中添加一些代码,如下例所示:

/*
 * Set Page templates for CPT "your_cpt"
 */


add_filter( 'template_include', 'my_plugin_templates' );
function my_plugin_templates( $template ) {

    $post_type = 'your_cpt'; // Change this to the name of your custom post type!

    if ( is_post_type_archive( $post_type ) && file_exists( plugin_dir_path(__DIR__) . "templates/archive-$post_type.php" ) ){
        $template = plugin_dir_path(__DIR__) . "templates/archive-$post_type.php";
    }

    if ( is_singular( $post_type ) && file_exists( plugin_dir_path(__DIR__) . "templates/single-$post_type.php" ) ){
        $template = plugin_dir_path(__DIR__) . "templates/single-$post_type.php";
    }

    return $template;
}
Run Code Online (Sandbox Code Playgroud)

希望这个例子对您有帮助。干杯!