Reputation: 197
I am using the following code to check if a product ID is in the cart, and if so, add extra checkout fields:
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' ));
}
}
This works just fine. However, how do I check for multiple product ID's in the cart? For instance, if product ID 326 or 245 are in the cart, show the conditional checkout fields? I feel like it is probably something simple, but I'm not sure how to go about doing it.
Upvotes: 3
Views: 3456
Reputation: 253968
I have make some changes in your function to get it work for many product IDs. Also I have added the required option to the field. So your code sould be something like:
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>';
}
}
Code goes in function.php file of your active child theme (active theme or in any plugin file).
This code is tested and works.
Upvotes: 5