希望恢复购物车商品的产品属性

时间:2017-08-14 15:25:48

标签: php woocommerce

我正在尝试恢复Woocomerce购物车中产品的一系列属性

这是我写的代码(我是初学者)

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
global $product;
$my_product_id = $cart_item['product_id'];
echo "ID is {$my_product_id} \n";
$my_attribute = WC()->product->attribute->get_name($value); 
}

但是我得到“在null上调用成员函数 get_name()

我想我的项目 product_id 没问题(使用 echo 查看)。但我不知道如何使用函数get_name()或实际上对象中的任何方法 WC_Product_Attribute

我想我在循环之外工作?

我正在将这段代码写入WordPress'页面'以便开发它,使用一个将代码包装在标签中的插件 - [insert_php]& [/ insert_php]

非常感谢,但我需要从概念上理解我的错误。

来自LoicTheAztec的正确代码作为数组的第三个元素(我想要检索的属性)生成

'pa_1_scale' => 
object(WC_Product_Attribute)[1410]
  protected 'data' => 
    array (size=6)
      'id' => int 1
      'name' => string 'pa_1_scale' (length=10)
      'options' => 
        array (size=1)
          ...
      'position' => int 2
      'visible' => boolean true
      'variation' => boolean false

1 个答案:

答案 0 :(得分:0)

正确的代码是:

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    // HERE the WC_Product object
    $product = $cart_item['data'];
    $product_id = $cart_item['product_id']; 

    $attributes = $product->get_attributes();
    foreach($attributes as $taxonomy => $value){
        // The WP_Term object
        $term_obj = get_term_by( 'slug', $value, $taxonomy );
        $term_name = $term_obj->name;
    }
}

经过测试和工作

相关问题