如何让WordPress使用自定义的single.php模板,如果帖子属于特定类别或其子类


How to have WordPress use a custom single.php template if the post is in a specific category OR its children?

我有一个标准的single.php,我正在开发的这个网站上的大多数帖子都会使用它,但对于特定的类别及其子类别,我想使用自定义的single.php。我该如何做到这一点?我知道我想要什么背后的逻辑,我只是不确定如何写。

这是我正在使用但不起作用的代码:

<?php
$post = $wp_query->post;
if ( in_category('2,6,7,8') ) {
include(TEMPLATEPATH . '/single-blog.php'); } 
else {
include(TEMPLATEPATH . '/single-default.php');
}
?>

Cat ID 6、7和8是Cat ID 2的子类别。

任何帮助都将不胜感激!

谢谢,

Cynthia

我认为您需要筛选template_include或更好的single_template。我将把has_category()条件保留为硬编码,但可以做一些事情来获得顶级类别,并始终测试它。

EDIT现在使用一个codex示例中的post_is_in_descendant_category()。注意,这不是一个内置的WordPress功能,所以你需要将其包含在你的插件/主题中。

编辑#2使用locate_template()确保文件确实存在。

function get_custom_category_template($single_template) {
     if ( in_category( 'blog' ) || post_is_in_descendant_category( 2 ) ) {
          $new_template = locate_template( array( 'single-blog.php' ) );
          if ( '' != $new_template ) {
            $single_template = $new_template ;
          }
     }
     return $single_template;
}
add_filter( 'single_template', 'get_custom_category_template' );
/* Checks if a category is a descendant of another category */
if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, 'category' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}

更新

你可以选择single-[post-type].php

阅读有关模板文件层次结构的更多信息

我想通了!helgatheviking关于顶级范畴的建议让我思考了祖先和后代范畴。从那里我发现了post_is_in_descendant_category函数。

在我的functions.php中放入以下函数后:

/* Checks if a category is a descendant of another category */
if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, 'category' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}

我想好了如何修改我原来的类别查询和模板分配,如下所示:

<?php
$post = $wp_query->post;
if ( in_category( 'blog' ) || post_is_in_descendant_category( 2 ) ) {
include(TEMPLATEPATH . '/single-blog.php'); } 
else {
include(TEMPLATEPATH . '/single-default.php');
}
?>

感谢所有试图提供帮助的人。我非常感激!