Reputation: 518
I need to add extra class like dropdown
to <li>
element, if this category has subcategories:
<ul class="departments__links">
<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if ($cat->category_parent == 0) {
$category_id = $cat->term_id;
echo '<li class="departments__item EXTRA-CLASS-HERE"><a href="'. get_term_link( $cat->slug, 'product_cat' ) .'" class="departments__item-link">'. $cat->name . '</a></li>';
}
}
?>
</ul>
This code comes from: https://stackoverflow.com/a/21012252/9598872
Upvotes: 0
Views: 173
Reputation: 371
You can use like this
<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$all_categories = get_categories( $args );
$extraclass = '';
foreach ($all_categories as $cat) {
if ($cat->category_parent == 0) {
$category_id = $cat->term_id;
$children = get_terms( $taxonomy, array(
'parent' => $category_id,
'hide_empty' => false
) );
if($children) {
$extraclass = "dropdown";
}else{
$extraclass = "";
}
echo '<li class="departments__item '.$extraclass.'"><a href="'. get_term_link( $cat->slug, 'product_cat' ) .'" class="departments__item-link">'. $cat->name . '</a></li>';
}
}
?>
Upvotes: 1