Right way to add class to post container HTML tag is post_class()
function, it’s also required by Theme Review Guidelines.
Many people ask on WordPress – Stack Exchange how to echo class depending on parent category, best way to do this is to use post_class
filter, so I wrote small chunk of code to this.
Following code is based on Chip Bennett’s clever solution. I changed big part of it, but logic is the same.
|
<?php |
|
/** |
|
* Add parent category class to post_class() function |
|
* |
|
* @link http://wordpress.stackexchange.com/q/23259#23260 |
|
*/ |
|
function mamaduka_add_parent_category_class( $classes, $class, $post_id ) { |
|
foreach ( (array) get_the_category( $post_id ) as $cat ) { |
|
if ( ! empty( $cat->parent ) ) { |
|
$parent_cat = &get_category( $cat->parent ); |
|
$classes[] = 'category-parent-' . sanitize_html_class( $parent_cat->slug, $parent_cat->term_id ); |
|
} else { |
|
$classes[] = 'category-parent-' . sanitize_html_class( $cat->slug, $cat->term_id ); |
|
} |
|
} |
|
|
|
return $classes; |
|
} |
|
add_filter( 'post_class', 'mamaduka_add_parent_category_class', 10, 3 ); |
What the code above does is simple, it gets array of category objects assigned to the post, then if category has parent it adds class ‘category-parent-{parent-cat-name}’, otherwise category is top-level so we are using it.
Problem: If user adds both parent and its child categories, we’ll get duplicated class output of parent category.
This is small problem I’m working now, any suggestions are welcome.