I am trying to add the parent category class in post_class() of some posts from one of my subcatgories. I have an advanved theme so I need to style all the posts from the parent cateogry using it’s class, not the subcategory class (too much hassle in CSS).
2 Answers
Perhaps something like:
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;
}
Then, when you call post_class()
:
<?php post_class( mytheme_get_post_class_parent_cats() ); ?>
- Codex ref: wp_get_post_categories()
- Codex ref: get_category_parents()
- Codex ref: get_cat_name()