Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 多个自定义帖子类型的Wordpress模板_Php_Wordpress - Fatal编程技术网

Php 多个自定义帖子类型的Wordpress模板

Php 多个自定义帖子类型的Wordpress模板,php,wordpress,Php,Wordpress,我有多个wordpress模板文件: 单示例_1.php 单示例_2.php archiv-example_1.php archiv-example_2.php 这些完全相同,只是针对不同的自定义帖子类型。正因为如此,我想把它们结合在一起。我添加了以下功能: add_filter( 'template_include', function( $template ) { $my_types = array( 'example_1', 'example_2' ); $post_

我有多个wordpress模板文件:

  • 单示例_1.php
  • 单示例_2.php
  • archiv-example_1.php
  • archiv-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'; 
});
这将“重定向”每个单独的归档站点到同一个模板


如何将归档页重定向到archiv示例,将单个页面重定向到单个示例?

您需要使用
is\u post\u type\u archive($post\u type)
来检查是否为归档页提供了查询

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

这有两个部分-您将需要处理归档模板和单篇文章模板的模板

对于存档,请使用该功能检查当前请求是否为要返回的某个帖子类型的存档页。如果匹配,请返回您的通用存档模板

对于单篇文章,使用函数查看当前请求是否针对指定文章类型之一的单篇文章。如果匹配,则返回通用的单个帖子模板

在这两种情况下,如果
$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;
    }
});

对于OP:您可以向函数传递一个post类型数组。谢谢您的建议。如何为帖子类型添加过滤器?(正如我使用
$my_types=array('example_1','example_2')所做的那样)
?我自己无法实现这一点,如果你能再帮我一次,那就太好了!你编写代码时假设没有其他帖子类型,如果有一个
示例\u 3
有不同的模板,这将中断。@doublesharp是的,你没有错。你可以将数组传递给函数
is\u post\u type\u archive($my_type)
使用当前声明的
$my_type
变量,哦,您已经发布了该变量。是的,+1谢谢,这是非常好的解释!