如果 post 属于特定类别或其子类别,如何让 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 的子类别。

任何帮助将不胜感激!

谢谢,

辛西娅

已更新

你可以去 single-[post-type].php.

阅读更多关于 The Template File Hierarchy

我认为您需要过滤 template_include or even better single_template. I'm leaving the has_category() conditional as hard-coded, but you could do something to get the top-level category 并始终对其进行测试。

编辑 现在使用手抄本示例中的 post_is_in_descendant_category()。请注意,这不是内置的 WordPress 功能,因此您需要将其包含在 plugin/theme 中。

编辑#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;
    }
}

我想通了! 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');

}

?>

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