[英]How to show the category name of my custom post type on single.php wordpress
[英]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;
}
}
我想到了! 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.