2017-10-10 94 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文件(活動的主題或任何插件文件)。

此代碼已經過測試並可正常工作。

+0

完美工作。謝謝。 – jasonTakesManhattan

相關問題