从 WooCommerce 购物车获取变体属性标签名称和价值产品

Get variation attributes label name and value products from WooCommerce cart

我应该获取购物车中产品的所有数据(产品名称和单个产品的属性)。作为参考,我有这段代码允许每个产品只显示一个属性。

你能帮我找到查看所有属性的解决方案吗? 商店中共有10个属性

$taxonomy = 'pa_selezione-pezzi';

// Get an instance of the WC_Product Object (necessary if you don't have it)
// from a dynamic $product_id (or defined $product_id)
$product = wc_get_product($product_id);
// Iterating through the product attributes
foreach($product->get_attributes() as $attribute){
    // Targeting the defined attribute
    if( $attribute->get_name() == $taxonomy ){
        // Iterating through term IDs for this attribute (set for this product)
        foreach($attribute->get_options() as $term_id){
            // Get the term slug
            $term_slug = get_term( $term_id, $taxonomy )->slug;

            // Output
            $confirmation = str_ireplace("{term_slug}", $term_slug, $confirmation);
        }
    }
}

如果您要检索产品变体购物车项目中设置的产品属性,可以使用以下代码示例:

// loop through product attributes
foreach( WC()->cart->get_cart() as $item ) {
    if( ! empty($item['variation']) ) {
        // loop through product attributes
        foreach($item['variation'] as $attribute => $term_name )  {
            $taxonomy       = str_replace('attribute_', '', $attribute);
            $attribute_name = wc_attribute_label($taxonomy);
            $term_name      = get_term_by( 'slug, $term_name, $taxonomy)->name;
        }
    }
}

已测试并有效

感谢“LoicTheAztec 先生”的正确回答;

已经开发了您的代码,供朋友使用;

注意:属性 $值标签 添加:

//اضافه کردن نام ویژگی به اسم محصول
//Add attribute label name to product name

if( $product->is_type( 'variation' ) ){
        
$s ='';
$s1 = '';
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {

 // Get the attribute label
 $attribute_label_name = wc_attribute_label($taxonomy);

 //convert to array 
 $attribute_arr = json_decode(json_encode($attribute_obj),true);
 $term_name      = get_term_by( 'slug', $attribute_arr, $taxonomy)->name;

 $s = $s . $s1 .$attribute_label_name.':'.$term_name;
 $s1 = ', ';

}

$name = $name . '(' .$s. ')';
echo '<p>' . $name. '</p>';


}