WordPress 的文章模板檔案是 single.php,如果要不同的自定義文章型別使用不同的模板檔案可以把模板檔案放在主題根目錄 single-{post_type}.php,WordPress 檢測到就會自動使用。
但是外掛開發者怎麼實現給自定義文章型別設定單獨的模板檔案呢?這裡就要介紹兩個非常實用的過濾器。
{$type}_template
{$type}_template 過濾器是 get_query_template() 函式最終返回的模板檔案路徑,$type 指的是頁面型別,比如文章頁就是 $type 就是 single.
下邊的程式碼就是給 slider 自定義文章型別單獨設定一個 PHP 模板:
|
/** *WordPress 不同自定義文章型別使用不同的模板檔案 *https://www.weixiaoduo.com/custom-post-type-template/ */ functionBing_slider_custom_post_type_template($template){ if($GLOBALS['post']->post_type=='slider')$single_template=plugin_dir_path(__FILE__).'slider-template.php'; return$single_template; } add_filter('single_template','Bing_slider_custom_post_type_template'); |
以此類推,用 {$type}_template 過濾器還可以設定存檔 (archive) 、分類 (category) 和標籤 (tag) 等頁面模板。
template_include
template_include 是最終要引入的模板的路徑的過濾器,任何頁面的模板都可以用這個來修改。
比如下邊的程式碼用來給 slider 自定義文章型別單獨設定一個 PHP 模板:
|
/** *WordPress 不同自定義文章型別使用不同的模板檔案 *https://www.weixiaoduo.com/custom-post-type-template/ */ functionBing_slider_custom_post_type_template($template){ if(is_single()&&$GLOBALS['post']->post_type=='slider')$single_template=plugin_dir_path(__FILE__).'slider-template.php'; return$single_template; } add_filter('template_include','Bing_slider_custom_post_type_template'); |
template_include 可以過濾任何的模板檔案路徑,用它可以自定義所有模板檔案路徑。