2017-08-14 64 views
2

我試圖恢復屬性的陣列產品在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); 
} 

但是我得到的「調用一個成員函數GET_NAME()對空」

我覺得我得到PRODUCT_ID沒關係的項目(使用回聲查看)。但我不知道如何使用函數get_name()或實際上對象的任何方法WC_Product_Attribute

我想我在循環外工作?

我寫這個代碼到一個WordPress「頁面」爲了發展它,用它包裝的標籤代碼插件 - [insert_php] & [/ insert_php]

幫助非常感謝,但我需要從概念上理解我做錯了什麼。

從LoicTheAztec

正確代碼產生作爲數組的第三元件(I要檢索的屬性)

'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 
+0

你寫的這段代碼是否包含在一個函數中? – IsThisJavascript

+0

不,代碼包裝在標籤[insert_php]&[/ insert_php] – Cheerychops

+0

要獲取受保護的數據,可以使用WC_Data類中的'get_data()'方法 – LoicTheAztec

回答

1

爲正確的代碼:

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; 
    } 
} 

測試和工程

+0

這很有效,但我該如何深入挖掘數組檢索ID - 參見上面的附加輸出 – Cheerychops

+0

@Cheerychops剛剛更新...使用'$ term_obj'有一切...您可以創建一個'print_r($ term_obj);'查看所有可用數據。 – LoicTheAztec

+0

嗨肯定進展,但得到錯誤「警告:preg_match()期望參數2是字符串,在C:\ wamp \ www \ wizstaginglocal \ wp-includes \ formatting.php 1514行中給出的對象」 – Cheerychops