繁体   English   中英

如果帖子属于特定类别或其子类别,如何让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');

}

?>

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

非常感激任何的帮助!

谢谢,

辛西娅

我认为您需要过滤template_include甚至更好的single_template 我将has_category()条件保留为硬编码,但是您可以做一些事情来获取顶级类别并始终进行测试。

现在使用来自法典示例的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');

}

?>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM