gpt4 book ai didi

WordPress template_include - 如何正确 Hook

转载 作者:行者123 更新时间:2023-12-04 16:29:49 28 4
gpt4 key购买 nike

我目前正在编写一个 WP 插件,需要覆盖模板。

我的过滤器钩子(Hook)看起来像这样 - 它执行:

add_filter('template_include', 'mcd_set_template',10);

函数 mcd_set_template() 只是将所需的路径作为字符串返回 - 或者在文件不存在的情况下返回默认的 WP 模板。

我已经玩了好几个小时了,甚至可以包含那个备用模板(但它出现在页面底部)。

所以我的问题是,如何强制 WP 3.2.1 只加载另一个模板文件——以及需要哪个优先级?

更新:
我还注意到使用 var_dump 时...它几乎在文件末尾输出-但应该出现在开始的 HTML 标记之前...

根据这张票,它应该与 template_include Hook : http://core.trac.wordpress.org/ticket/11242

或者是 Hook 这些过滤器的唯一方法:
http://codex.wordpress.org/Template_Hierarchy#Filter_Hierarchy
?

最佳答案

您可以使用如上所示的 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() 的任何时候创建该分层模板数组。使用这种方法,很容易看出您可以多么容易地创建各种非常详细和特定的层次结构,无论是作为原生模板层次结构的一部分还是独立于原生模板层次结构。

关于WordPress template_include - 如何正确 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8320750/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com