我正在尝试将父类别类添加到我的子类别之一的一些帖子的post\\u class()中。我有一个高级的主题,所以我需要使用它的类而不是子类(CSS中有太多麻烦)来设置父类别中所有帖子的样式。
在POST_CLASS()中获取父类别类
2 个回复
最合适的回答,由SO网友:Chip Bennett 整理而成
可能类似于:
function mytheme_get_post_class_parent_cats() {
$parent_cat_classes = array();
// Get parent categories
$post_cats = wp_get_post_categories();
// Loop through post categories
foreach ( $post_cats as $post_cat ) {
$cat_parents = get_category_parents( $post_cat , false, \',\', true );
// if there are any parent categories
if ( $cat_parents ) {
// create an array
$cat_array = explode( $cat_parents, \',\' );
// First key of the array is the top-level category parent
$parent_cat_id = $cat_array[0];
// Get the name of the top-level parent category
$parent_cat = get_cat_name( $parent_cat_id );
// create the CSS class .category-parent-{categoryname}
$parent_cat_classes[] = \'category-parent-\' . $parent_cat;
} else {
// Otherwise, the category is a top-level cat, so use it
$cat_name = get_cat_name( $post_cat );
$parent_cat_classes[] = \'category-parent-\' . $cat_name;
}
}
// Return CSS class, or false
return $parent_cat_classes;
}
那么,当你打电话的时候post_class()
:<?php post_class( mytheme_get_post_class_parent_cats() ); ?>
法典参考号:wp_get_post_categories()get_category_parents()get_cat_name()SO网友:rats
一位朋友找到了完美的解决方案,所以我认为与你们分享是公平的:
function rats_class($classes){
global $post;
$cat=get_the_category(get_query_var(\'post\'));
if(is_array($cat)&&!empty($cat)){
if($cat[0]->category_parent!=0){
$parents=get_category_parents($cat[0]->term_id,false,\'@\',true);
if(!empty($parents)){
$parent=explode(\'@\',$parents);
$classes[]=\'category-\'.$parent[0];
}
}
}
return $classes;
}
add_filter(\'post_class\',\'rats_class\');
结束