Answer the question
In order to leave comments, you need to log in
How can I set the class only to parent categories in a custom loop?
By design, I need to display categories with subcategories on an individual page. The nuance is that subcategories and categories without child categories were displayed with pictures, and parent categories without pictures.
I output it like this
<div class="cat-container">
<?php
$categories = get_terms(
'product_cat',
array(
'orderby' => 'menu_order',
'order' => 'ask',
'hierarchical' => true,
'hide_empty' => 1,
'parent' => 0
)
);
foreach($categories as $cat){
$cat_thumb_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$cat_thumb_url = wp_get_attachment_image_src( $cat_thumb_id, 'thumbnail-size' )[0];
?>
<div class="cat-sub">
<?php $temp_cat = get_terms(
'product_cat',
array(
'orderby' => 'menu_order',
'order' => 'ask',
'hierarchical' => true,
'hide_empty' => 1,
'parent' => $cat->term_id
)
);
$class='';
if($temp_cat) {$class='has_child';} else {$class='no_child';} ?>
<div class="parent-item-wrap d-flex justify-content-center">
<div class="cat-parent-item col-lg-5 col-12 product-category">
<div class="subcategory-inner">
<a href="<?php echo get_term_link( $cat->term_id,'product_cat' )?>" target='_blank'>
<img src="<?php echo $cat_thumb_url; ?>" alt="" />
<h2 class="woocommerce-loop-category__title"><?php echo $cat->name?></h2>
</a>
</div>
</div>
</div>
<?php
if($temp_cat){?>
<div class="child-items d-flex flex-wrap align-items-stretch">
<?php foreach($temp_cat as $temp){
$cat_thumb_id = get_woocommerce_term_meta( $temp->term_id, 'thumbnail_id', true );
$cat_thumb_url = wp_get_attachment_image_src( $cat_thumb_id, 'thumbnail-size' )[0];
?>
<div class="cat-item col-xl-3 col-md-4 col-sm-6 col-12 product-category">
<div class="subcategory-inner">
<a href="<?php echo get_term_link( $temp->term_id,'product_cat' )?>" target='_blank'>
<img src="<?php echo $cat_thumb_url; ?>" alt="" />
<h2 class="woocommerce-loop-category__title"><?php echo $temp->name; ?></h2>
</a>
</div>
</div>
<?php }?>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<img src="<?php echo $cat_thumb_url; ?>" alt="" />
Answer the question
In order to leave comments, you need to log in
The object that returns get_terms()
has a key parent , by which you can check the existence of the parent category
$categories = get_terms();
foreach ( $categories as $key => $category ) {
if ( $category->parent == 0 ) {
# нет родителя
} else {
# есть родитель
}
}
function is_category_parent( $cat_id ) {
$category = get_category( $cat_id );
if ( $category->parent == 0 ) {
return true;
}
return false;
}
if ( is_category_parent( $cat_id ) ) {
// категория имеет родителя
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question