你可以使用template_redirect如上圖所示,但也不需要退出,它不會踐踏WordPress通常會做的所有事情來查找當前模板。您可能希望讓這種情況發生,然後將邏輯應用到當前模板。
使用上述一些什麼......
add_action('template_include', 'mcd_set_template');
function mcd_set_template() {
return locate_template('templatename.php');
}
這是相當簡單的,你也可以傳遞一個數組locate_template()來定義一個層次。如果你要使用'template_redirect'如上所示,你應該仍然使用locate_template,這是如何。
add_action('template_redirect', 'mcd_set_template');
function mcd_set_template() {
/**
* Order of templates in this array reflect their hierarchy.
* You'll want to have fallbacks like index.php in case yours is not found.
*/
$templates = array('templatename.php', 'othertemplate.php', 'index.php');
/**
* The first param will be prefixed to '_template' to create a filter
* The second will be passed to locate_template and loaded.
*/
include(get_query_template('mcd', $templates));
exit;
}
最後,最好的方法是過濾特定類型而不是整個層次結構。例如,您可以過濾'category_template'或'page_template'。這將是更爲具體,這將避免與整個模板層次搞亂,如果你不想 - 它可以讓WordPress的做多繁重的
例如:
add_filter('category_template', 'filter_category_template');
function filter_category_template($template){
/* Get current category */
$category = get_queried_object();
/* Create hierarchical list of desired templates */
$templates = array (
'category.php',
'custom-category-template.php',
'category-{$category->slug}.php',
'category-{$category->term_id}.php',
'index.php'
);
return locate_template($templates);
}
你可以的當您使用locate_template()時,可以創建分層模板陣列。使用這種方法,可以很容易地看出,作爲本地模板層次結構的一部分或者與之分離,您可以輕鬆創建各種非常詳細和特定的層次結構。
很抱歉,調用exit()或die()絕對不是一種選擇 - 因爲它會盡快殺死腳本中的一個查詢... 需要過濾template_loader。php @ line 42 –
請注意標題中的*正確*這個詞 - 你粘貼的代碼確實很蹩腳。爲什麼?由於hook template_redirect發生在模板加載器決定要加載哪個模板之前發生...... –
我在BuddyPress bug-tracker中看到您之前使用過您的建議 - 但優先級爲999--而不是默認值10. –