Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amouratoglou/0f9d43c24bd25d2bcc58c42aa1618bbb to your computer and use it in GitHub Desktop.
Save amouratoglou/0f9d43c24bd25d2bcc58c42aa1618bbb to your computer and use it in GitHub Desktop.
woocommerce get all current product parent and child categories
<?php
// intended to be placed in short-description on the single product page
global $post, $product;
$id = $product->id;
$categories = get_the_terms( $product->get_id(), 'product_cat' );
$firstlevelcategories = [];
$secondlevelcategories = [];
foreach ( $categories as $sub_category ) {
if($sub_category->parent != 0){
array_push($secondlevelcategories, $sub_category);
}
}
foreach ( $categories as $sub_category ) {
if($sub_category->parent == 0){
array_push($firstlevelcategories, $sub_category);
}
}
foreach ($firstlevelcategories as $category) {
echo '<p class="parent-cat-name">'.$category->name.'</p>';
?>
<div class="category-wrapper">
<?php
// find categories
foreach ( $secondlevelcategories as $subcat ) {
if ($category->term_id == $subcat->parent){
$thumbnail_id = get_term_meta($subcat->term_id, 'thumbnail_id', true);
$image = wp_get_attachment_image_src( $thumbnail_id, 'medium' );
$term_link = get_term_link( $subcat, $taxonomy );
$term_name = $subcat->name;
?>
<div class="cat-wrapper">
<div class="product-cats">
<a class="cat-links" href="<?php echo $term_link; ?>">
<div class="sub-cat-wrapper">
<img src="<?php echo $image[0];?>">
<p><?php echo $term_name;?></p>
</div>
</a>
</div>
</div>
<?php
}
}
?>
</div> <?php
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment