List product categories hierarchy from a product id in Woocommerce

前端 未结 1 421
野的像风
野的像风 2021-01-15 13:56

I have a products that can be in multiple categories, example take a look at the following strings:

  • Cat1>Product1
  • Cat1>Product2
  • Cat2>subcat1>
相关标签:
1条回答
  • 2021-01-15 14:42

    To get all ancestors of a product category, you can use the Wordpress get_ancestors() function

    The following custom shortcode function will output for each product category of a given product, the ancestors with the product category in a string as defined in your question:

    add_shortcode( 'product_cat_list', 'list_product_categories' )
    function list_product_categories( $atts ){
        $atts = shortcode_atts( array(
            'id' => get_the_id(),
        ), $atts, 'product_cat_list' );
    
        $output    = []; // Initialising
        $taxonomy  = 'product_cat'; // Taxonomy for product category
    
        // Get the product categories terms ids in the product:
        $terms_ids = wp_get_post_terms( $atts['id'], $taxonomy, array('fields' => 'ids') );
    
        // Loop though terms ids (product categories)
        foreach( $terms_ids as $term_id ) {
            $term_names = []; // Initialising category array
    
            // Loop through product category ancestors
            foreach( get_ancestors( $term_id, $taxonomy ) as $ancestor_id ){
                // Add the ancestors term names to the category array
                $term_names[] = get_term( $ancestor_id, $taxonomy )->name;
            }
            // Add the product category term name to the category array
            $term_names[] = get_term( $term_id, $taxonomy )->name;
    
            // Add the formatted ancestors with the product category to main array
            $output[] = implode(' > ', $term_names);
        }
        // Output the formatted product categories with their ancestors
        return '"' . implode('" | "', $output) . '"';
    }
    

    Code goes in function.php file of your active child theme (active theme). Tested and works.


    USAGE:

    1) In the php code of product page:

    echo do_shortcode( "[product_cat_list]" );
    

    2) In php code with a given product ID (here the product ID is 37 for example):

    echo do_shortcode( "[product_cat_list id='37']" );
    

    I think that the product name is not needed in your output as it is repetitive (on each product category). So you will get something like this:

    "Cat1" | "Cat2>subcat1" | "Cat3>subcat1>subcat2"
    
    0 讨论(0)
提交回复
热议问题