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 可以過濾任何的模板文件路徑,用它可以自定義所有模板文件路徑。