問題描述

我正在編寫一個外掛來管理有關 open-source 專案的資料。我開發了一個物件模型,並已經成功地建立了所有自定義的帖子型別和分類,以及使用 Members 外掛實現了正確的功能/角色。適當的使用者可以建立,修改和刪除自己的帖子,管理員可以批准他們,以及修改和刪除任何人的帖子。

我的問題是,我想定義一個專案的模板和專案列表 (單個和存檔,我相信 – 我從來沒有在這個級別使用 Wordpress),但我不希望迴圈依賴在目前的主題中為單個專案或專案列表呈現頁面。如果我使用 TwentyTen 主題,我希望它使用我的外掛的模板為這些自定義的帖子型別。如果我使用 TwentyEleven 主題,我仍然希望它使用我的外掛的模板為這些自定義的帖子型別。

我想要這樣服從 「它只是工作」 的範例,但現在使用者不能只是將資料夾放在外掛目錄中 – 他們必須在每次切換主題時將適當的檔案新增到其主題資料夾中。我已經簽出了模板層次結構,並且檔名正確無誤,但如果它們位於 plugin 資料夾或 plugin /templates 資料夾中,則 WordPress 不會使用它們。

謝謝!

最佳解決方案

您需要使用 template_include 過濾器,它是所有模板包含體的通用過濾器。

add_filter( 'template_include', 'my_plugin_templates' );
function my_plugin_templates( $template ) {
    $post_types = array( 'project' );

    if ( is_post_type_archive( $post_types ) && ! file_exists( get_stylesheet_directory() . '/archive-project.php' ) )
        $template = 'path/to/list/template/in/plugin/folder.php';
    if ( is_singular( $post_types ) && ! file_exists( get_stylesheet_directory() . '/single-project.php' ) )
        $template = 'path/to/singular/template/in/plugin/folder.php';

    return $template;
}

我還沒有完全測試帖子型別歸檔位,您可能需要使用 is_tax( $taxonomies )包含一個檢查,使其能夠處理相關的自定義分類歸檔。

參考文獻

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