WordPress template_include - 如何正确挂钩

Mar*_*ler 5 wordpress templates add-filter

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

我的过滤器钩子看起来像 - 并执行:

add_filter('template_include', 'mcd_set_template',10);
Run Code Online (Sandbox Code Playgroud)

function mcd_set_template()只返回字符串所需的路径 - 如果文件不存在,则返回默认的WP模板.

我已经玩了好几个小时,甚至可以包括那个替代模板(但它出现在页面的底部).

所以我的问题是,如何强制WP 3.2.1只加载另一个模板文件代替 -和优先需要?

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

根据这张票,它应该与template_include钩子一起使用:http://core.trac.wordpress.org/ticket/11242

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

edd*_*oya 14

您可以使用如上所示的template_redirect,但这确实需要退出,并且它会践踏WordPress通常用于查找当前模板的所有其他内容.您可能希望发生这种情况,然后将逻辑应用于当前模板.

使用上面的一些......

add_action('template_include', 'mcd_set_template');

function mcd_set_template() {
    return locate_template('templatename.php');
}
Run Code Online (Sandbox Code Playgroud)

这很简单,您也可以将数组传递给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;
}
Run Code Online (Sandbox Code Playgroud)

最后,最好的方法是过滤特定类型而不是整个层次结构.例如,您可以过滤'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);
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以在使用locate_template()时创建分层模板数组.使用此方法,很容易看出您可以轻松创建各种非常详细和特定的层次结构,作为本机模板层次结构的一部分或与之分离.


Jus*_*afe 4

您是否尝试过使用 add_action 来代替?例如,您可能想在插件中尝试类似以下内容:

add_action('template_redirect', 'mcd_set_template');
//Redirect to a preferred template.
function mcd_set_template() {
    $template_path = TEMPLATEPATH . '/' . "templatename.php";
    if(file_exists($template_path)){
        include($template_path);
        exit;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个有用的参考:http://www.mihaivalentin.com/wordpress-tutorial-load-the-template-you-want-with-template_redirect/

  • 请注意标题中的“正确”一词 - 您粘贴的代码的作用相当蹩脚。为什么?因为钩子 template_redirect 发生在模板加载器决定加载哪个模板之前...... (2认同)