Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function woocommerce_category_id() {
- global $post;
- $prod_terms = get_the_terms( $post->ID, 'product_cat' );
- if ($prod_terms != null) {
- foreach ($prod_terms as $prod_term) {
- // gets product cat id
- $product_cat_name = $prod_term->term_id;
- // gets an array of all parent category levels
- $product_parent_categories_all_hierachy = get_ancestors( $product_cat_name, 'product_cat' );
- // This cuts the array and extracts the last set in the array
- $last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
- foreach($last_parent_cat as $last_parent_cat_value){
- // $last_parent_cat_value is the id of the most top level category, can be use whichever one like
- $product_id = $last_parent_cat_value;
- $args = array('hierarchical' => 1, 'show_option_none' => '', 'hide_empty' => 0, 'parent' => $product_id, 'taxonomy' => 'product_cat' );
- $subcats = get_categories($args);
- if ( is_product_category() ) {
- foreach ($subcats as $sc) {
- if(get_queried_object()->slug == $sc->slug) { $class = ' class="current"'; }
- else { $class = ''; }
- $link = get_term_link( $sc->slug, $sc->taxonomy );
- echo '<li'.$class.'><a href="'. $link .'">'.$sc->name.'</a></li>';
- }
- } elseif ( is_product() ){
- foreach ($subcats as $sc) {
- if(get_queried_object()->slug == $sc->slug) { $class = ' class="current"'; }
- else { $class = ''; }
- $link = get_term_link( $sc->slug, $sc->taxonomy );
- echo '<li'.$class.'><a href="'. $link .'">'.$sc->name.'</a></li>';
- }
- } else {
- $args2 = array('hierarchical' => 1, 'show_option_none' => '', 'hide_empty' => 0, 'parent' => 0, 'taxonomy' => 'product_cat' );
- $subproducts = get_terms( 'product_cat', $args2);
- foreach ($subproducts as $subproduct) {
- $link2 = get_term_link( $subproduct->slug, $subproduct->taxonomy );
- echo '<li><a href="'.$link2.'">'.$subproduct->name.'</a></li>';
- }
- }
- }
- }
- else {
- echo '<p>No items found.</p>';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement