2016-12-23 7 views
2

WOOCommerceでは、ショッピングカートの商品に'Varifocal'の属性があるかどうかをチェックしたいと思います(チェックアウトフィールドの表示/非表示が可能です) 。カート内の特定の属性値が使用されていることを確認する

私は、属性 'varifocal'を持つすべてのバリエーションのidの配列を取得するのに苦労しています。誰かが私を正しい方向に向けることができれば、本当に感謝しています。

分類法はpa_lensesです。

私は現在、次の機能があります。

function varifocal() { 
    // Add product IDs here 
    $ids = array(); 

    // Products currently in the cart 
    $cart_ids = array(); 

    // Find each product in the cart and add it to the $cart_ids array 
    foreach(WC()->cart->get_cart() as $cart_item_key => $values) { 
     $cart_product = $values['data']; 
     $cart_ids[] = $cart_product->get_id(); 
    } 

    // If one of the special products are in the cart, return true. 
    if (! empty(array_intersect($ids, $cart_ids))) { 
     return true; 
    } else { 
     return false; 
    } 
} 

答えて

1

を - コードを更新しました - ここで

は、特定の属性trueを返しますカスタム条件関数であります引数が1つのカートアイテムに見つかりました(製品バリエーション)

function is_attr_in_cart($attribute_value){ 

    $found = false; 

    if(WC()->cart->is_empty()) return $found; 
    else { 

     foreach (WC()->cart->get_cart() as $cart_item){ 
      // Product ID 
      $product_id = $cart_item['product_id']; 

      // Variation ID + attributes 
      if(0 != $cart_item['variation_id']){ 
       $variation_id = $cart_item['variation_id']; 
       foreach($cart_item['variation'] as $attribute_val){ 
        // comparing attribute parameter value with current attribute value 
        if ($attribute_val == $attribute_value) { 
         $found = true; 
         break; 
        } 
       } 
      } 
      if($found) break; 
     } 

     return $found; 
    } 
} 

アクティブな子テーマ(アクティブなテーマまたはすべてのプラグインファイル)のfunction.phpファイルにコードが入ります。

コードがテストされ、動作します。


USAGE(例)

if(is_attr_in_cart('Varifocal')){ 
    echo '"Varifocal" attribute value has been found in cart items<br>'; 
} else { 
    echo '"Varifocal" <strong>NOT FOUND!!!</strong><br>'; 
} 

アドバイス:カートが空の場合この条件関数はfalseを返します

+0

もっと良い解決策。私はそれをテストし、それは動作します。どうもありがとうございました! – PieterM