2017-10-10 4 views
1
でカート内の商品IDの複数の確認

私はプロダクトIDがカートにあるかどうかをチェックし、もしそうなら、余分なチェックアウトフィールドを追加するには、次のコードを使用しています:WooCommerce

add_action('woocommerce_after_order_notes', 'conditional_checkout_field'); 

function conditional_checkout_field($checkout) { 
    echo '<div id="conditional_checkout_field">'; 

    $product_id = 326; 
    $product_cart_id = WC()->cart->generate_cart_id($product_id); 
    $in_cart = WC()->cart->find_product_in_cart($product_cart_id); 

    // Check if the product is in the cart and show the custom field if it is 

    if ($in_cart) { 
      echo '<h3>'.__('Products in your cart require the following information').'</h3>'; 

      woocommerce_form_field('custom_field_license', array(
      'type'   => 'text', 
      'class'   => array('my-field-class form-row-wide'), 
      'label'   => __('License Number'), 
      'placeholder' => __('Placeholder to help describe what you are looking for'), 
      ), $checkout->get_value('custom_field_license')); 

    } 
} 

これだけで正常に動作します。ただし、カート内の複数の商品IDを確認するにはどうすればよいですか?たとえば、商品ID 326または245がカートにある場合は、条件付きチェックアウトのフィールドを表示しますか?私はそれがおそらく単純な何かのように感じるが、私はそれをやり遂げる方法についてはわからない。

答えて

1

私は多くの製品IDで機能するように機能をいくつか変更しました。また、フィールドに必要なオプションを追加しました。

add_action('woocommerce_after_order_notes', 'conditional_checkout_field', 10, 1); 
function conditional_checkout_field($checkout) { 

    // Set here your product IDS (in the array) 
    $product_ids = array(37, 53, 70); 
    $is_in_cart = false; 

    // Iterating through cart items and check 
    foreach(WC()->cart->get_cart() as $cart_item_key => $cart_item) 
     if(in_array($cart_item['data']->get_id(), $product_ids)){ 
      $is_in_cart = true; // We set it to "true" 
      break; // At east one product, we stop the loop 
     } 

    // If condition match we display the field 
    if($is_in_cart){ 
     echo '<div id="conditional_checkout_field"> 
     <h3 class="field-license-heading">'.__('Products in your cart require the following information').'</h3>'; 

     woocommerce_form_field('custom_field_license', array(
      'type'   => 'text', 
      'class'   => array('my-field-class form-row-wide'), 
      'required'  => true, // Added required 
      'label'   => __('License Number'), 
      'placeholder' => __('Placeholder to help describe what you are looking for'), 
     ), $checkout->get_value('custom_field_license')); 

     echo '</div>'; 
    } 
} 

コードは、あなたのアクティブな子テーマ(アクティブテーマや任意のプラグインファイル内)のfunction.phpファイルに行く:だからあなたのコードは次のようなものになるsould。

このコードはテスト済みであり、動作します。

+0

完全に作業しました。ありがとう。 – jasonTakesManhattan