2015-11-03 94 views
1

我有多个WordPress的模板文件:WordPress模板

  • 单example_1.php
  • 单example_2.php
  • 档案馆,example_1.php
  • 档案馆,example_2 .php

这些都是完全一样的,它们只是针对不同的自定义帖子类型。正因为如此,我想将它们合并为一个。我已添加此功能:

add_filter('template_include', function($template) 
{ 
    $my_types = array('example_1', 'example_2'); 
    $post_type = get_post_type(); 

    if (! in_array($post_type, $my_types)) 
      return $template; 
    return get_stylesheet_directory() . '/single-example.php'; 
}); 

此“重定向”每个单一和档案站点到相同的模板。

如何将归档页面仅重定向到档案示例页面和单页面示例?

回答

2

有两个部分这 - 你将需要处理的模板都存档的模板以及单后的模板。

对于档案,使用is_post_type_archive($post_types)函数检查并查看当前请求是否针对您要返回的某个帖子类型的存档页。如果匹配,则返回您的通用归档模板。

对于单个帖子,使用is_singular($post_types)函数查看当前请求是否针对您指定的某个帖子类型的单个帖子。如果匹配,则返回常见单个帖子模板。

在这两种情况下,如果它不是匹配以防被另一个过滤器修改,则会返回$template

add_filter('template_include', function($template) { 
    // your custom post types 
    $my_types = array('example_1', 'example_2'); 

    // is the current request for an archive page of one of your post types? 
    if (is_post_type_archive( $my_types)){ 
     // if it is return the common archive template 
     return get_stylesheet_directory() . '/archive-example.php'; 
    } else 
    // is the current request for a single page of one of your post types? 
    if (is_singular($my_types)){ 
     // if it is return the common single template 
     return get_stylesheet_directory() . '/single-example.php'; 
    } else { 
     // if not a match, return the $template that was passed in 
     return $template; 
    } 
}); 
+0

非常感谢,这很好解释! –

0

您将希望使用is_post_type_archive($post_type)来检查是否正在为归档页面提供查询。

if (is_post_type_archive($post_type)) 
    return get_stylesheet_directory() . '/archive-example.php'; 
return get_stylesheet_directory() . '/single-example.php'; 
+0

对于OP:可以通过柱类型的数组到['is_post_type_archive()'](https://codex.wordpress.org/Function_Reference/is_post_type_archive)函数。 – rnevius

+0

感谢您的建议。我如何为帖子类型添加过滤器? (正如我使用'$ my_types = array('example_1','example_2')'所做的那样'''我自己无法实现这个功能,如果你能帮助我另外一次,这将非常棒! –

+0

You代码假设没有其他的帖子类型,如果有一个'example_3'具有不同的模板,这将会中断 – doublesharp