問題描述

我一直在嘗試建立一個自定義帖子型別作為外掛 (因為我已經看到這在各個地方推薦) 。

但是我有一個問題不在於如何,而是建立 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。