[英]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.