問題描述

我一直在嘗試創建一個自定義帖子類型作為插件 (因為我已經看到這在各個地方推薦) 。

但是我有一個問題不在於如何,而是建立 CPT 作為插件的原因。

是… 添加 CPT 作為插件確實保持我的 functions.php 好整潔。

但…

  1. 假設我啓用了 has_archive,我還需要創建 archive-cpt.php,對吧?

  2. 另外:為了顯示 CPT,我需要創建一個自定義循環,所以我仍然需要創建 single-cpt.php … 對吧?

  3. 這些文件需要在主題中創建,對吧?

如果我正確理解,

  1. 如果我禁用插件:我仍然必須刪除 (或隱藏或某事)archive-cpt.phpsingle-cpt.php 頁面。

  2. 如果我切換主題:我還需要將這兩個頁面添加到新主題中。對?

我甚至沒有碰到將默認循環添加到 CPT 的問題 (這對 plugin-based cpt 有影響) 。

那麼為什麼一個 CPT 插件?

最佳解決方案

對於在插件中定義 CPT 的技術原因,toscho 的答案是正確的,但在我看來,您的大部分問題源於對模板層次結構的誤解。幾乎,但不完全,您看到的每個模板文件是可選的。

With the exception of the basic index.php template file, Theme developers can choose whether they want to implement a particular template file or not. If WordPress cannot find a template file with a matching name, it skips down to the next file name in the hierarchy. If WordPress cannot find any matching template file, index.php (the Theme’s home page template file) will be used.

http://codex.wordpress.org/Template_Hierarchy

如果沒有專門的文件,WordPress 將使用特定的專用文件 (如果它們存在但是 fall-back 到另一個文件 – 最終 index.php) 。您的主題不需要執行任何特殊的處理或補償您的插件’s CPT’s 。主題可以但不必。

  1. Assuming I’ve enabled has_archive I still need to create archive-cpt.php, right?

將使用 archive.php 號,如果失敗,則 index.php

  1. Also: In order to display the CPT I need to create a custom loop, so I still need to create single-cpt.php …right?

再次,沒有。同樣的原因將使用 single.php,如果不使用 index.php

  1. And these files need to be created in the theme, right?

是的,但它們是可選的。你根本不需要它們。

  1. If I disable the plugin: I still have to remove (or hide or something) the archive-cpt.php and single-cpt.php pages.

不,你不需要做任何事情。不會使用模板。

  1. If I switch Themes: I still have to add those two pages into the new theme. Right?

錯誤。模板是可選的。您只需要他們,如果你想要一個自定義顯示的職位類型。

當你明白主題和 CPT 不像你的問題那樣緊密相連時,似乎有些其他的邏輯應該更有意義。

次佳解決方案

當常量 SHORTINIT 設置為 TRUE(自定義 AJAX 處理程序,進口商或 API) 時,主題未加載,則不會將這些自定義帖子類型或分類法添加到任何帖子中。

模板是自定義內容的視圖,它們不應該定義或依賴邏輯。

此外,在主題切換之後,用户不能再訪問和更改帖子類型內容,因為在沒有註冊的情況下將沒有接口。

禁用插件後,您不必更改主題。模板不再被使用了。

更新:插件的另一個優點是能夠在網絡範圍內激活它們。我是 Multilingual Press 的主要開發人員,我們為用户提供翻譯和連接自定義帖子類型帖子的功能。但是如果它們被綁定到一個主題,這是無法工作的,因為一個主題總是對每個站點有效,而不是整個網絡。主題帖子類型真的很難翻譯。

參見:Where to put my code: plugin or functions.php?

參考文獻

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