Last active
September 21, 2021 01:43
-
-
Save amouratoglou/0f9d43c24bd25d2bcc58c42aa1618bbb to your computer and use it in GitHub Desktop.
woocommerce get all current product parent and child categories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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