問題描述

我想提供我的自定義帖子類型作為插件,以便人們可以使用它而不觸摸他們的主題文件夾。但是自定義帖子類型模板 (如 single-movies.php) 駐留在主題文件夾中。有沒有辦法讓 WP 檢查插件文件夾中的 single-movies.php?將功能掛接到 Filer Hierarchy 中?或者 get_template_directory(); ?

最佳解決方案

您可以使用 single_template 過濾鈎。

/* Filter the single_template with our custom function*/
add_filter('single_template', 'my_custom_template');

function my_custom_template($single) {
    global $wp_query, $post;

    /* Checks for single template by post type */
    if ($post->post_type == "POST TYPE NAME"){
        if(file_exists(PLUGIN_PATH . '/Custom_File.php'))
            return PLUGIN_PATH . '/Custom_File.php';
    }
    return $single;
}

次佳解決方案

在主題文件夾中添加一個自定義帖子類型特定模板的檢查到 @Brainternet 答案。

function load_person_template($template) {
    global $post;

    // Is this a "my-custom-post-type" post?
    if ($post->post_type == "my-custom-post-type"){

        //Your plugin path
        $plugin_path = plugin_dir_path( __FILE__ );

        // The name of custom post type single template
        $template_name = 'single-my-custom-post-type.php';

        // A specific single template for my custom post type exists in theme folder? Or it also doesn't exist in my plugin?
        if($template === get_stylesheet_directory() . '/' . $template_name
            || !file_exists($plugin_path . $template_name)) {

            //Then return "single.php" or "single-my-custom-post-type.php" from theme directory.
            return $template;
        }

        // If not, return my plugin custom post type template.
        return $plugin_path . $template_name;
    }

    //This is not my custom post type, do nothing with $template
    return $template;
}
add_filter('single_template', 'load_person_template');

現在,您可以讓插件用户將模板從您的插件複製到主題以覆蓋它。

有了這個例子,模板必須在插件和主題的根目錄下。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。