从 Woocommerce 中的产品 ID 列出产品类别层次结构

List product categories hierarchy from a product id in Woocommerce

我有一个产品可以分为多个类别,示例看一下以下字符串:

在woocommerce中,如果我有一个productid,我可以这样做:

    function alg_product_categories_names2( $atts ) {
    $product_cats = get_the_terms( $this->get_product_or_variation_parent_id( $this->the_product ), 'product_cat' );
    $cats = array();

    $termstest= '';
    if ( ! empty( $product_cats ) && is_array( $product_cats ) ) {
        foreach ( $product_cats as $product_cat ) {             
            if ( $term->parent == 0 ) { //if it's a parent category
                    $termstest .= ' PARENTCAT= '. $product_cat->name;
          }                             
        }
    }

    return htmlentities('<categories_names>'. $termstest .'</categories_names>');
}

但这只是 returns 产品 ID 的所有父类别。

cat1、cat2、subcat1、Cat3、subcat2

我很难接受。我需要的是给定一个产品 ID,构建上面的列表 - 应该返回的是:

"Cat1>Product1" | "Cat2>subcat1>Product1" | "Cat3>subcat1>subcat2>Product1"

我基本上需要从产品 ID 重建每个类别路径。

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

以下自定义短代码函数将为给定产品的每个产品类别输出,在您的问题中定义的字符串中具有产品类别的祖先:

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) . '"';
}

代码进入您的活动子主题(活动主题)的 function.php 文件。已测试并有效。


用法:

1) 产品页面php代码中:

echo do_shortcode( "[product_cat_list]" );

2) 在 php 代码中给定产品 ID (这里的产品 ID 是 37:

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"