5

I want add Custom field in WooCommerce checkout page but for selected products.

For e.g if Client have Product A in cart only than this custom field should appear in WooCommerce Checkout Page

I am using following code in functions.php to add custom field:

add_action('woocommerce_before_order_notes', 'my_delivery_checkout_field');

function my_delivery_checkout_field( $checkout ) {

echo '<div id="my_local_club"><h3>'.__('Delivery Options').'</h3>';

woocommerce_form_field( 'delivery_options', array(
'type' => 'select',
'class' => array('my-club-class form-row-wide'),
'label' => _('<br><br>Please select your options', 'woocommerce'),
'required' => true,
'placeholder' => _x('Please Select An Option...', 'placeholder','woocommerce'),
'options' => array(
'option1' => 'Option 1',
'option_2' =>'Option 2',
 'option_3' =>'Option 3'
)
), $checkout->get_value( 'delivery_options' ));

echo '</div>';

}
2
  • Delivery options should likely be handled using the (very robust) shipping system. Jan 1, 2016 at 19:05
  • Hi cale_b actually it is not for delivery options, client wants to add additional user input field in checkout page just to get notified that's it Jan 2, 2016 at 15:55

1 Answer 1

2

So following code solve my problem thanks to StackOverFlow.com

/**
* Add the field to the checkout
**/
add_action('woocommerce_before_order_notes', 'my_delivery_checkout_field');

function my_delivery_checkout_field( $checkout ) {

    //Check if gift card is in cart
    $book_in_cart = conditional_product_in_cart( 7267 );

if ( $book_in_cart === true ) {
echo '<div id="my_local_club"><h3>'.__('Delivery Options').'</h3>';

woocommerce_form_field( 'delivery_options', array(
'type' => 'select',
'class' => array('my-club-class form-row-wide'),
'label' => _('<br><br>Please select your options', 'woocommerce'),
'required' => true,
'placeholder' => _x('Please Select An Option...', 'placeholder','woocommerce'),
'options' => array(
'option1' => 'Option 1',
'option_2' =>'Option 2',
 'option_3' =>'Option 3'
)
), $checkout->get_value( 'delivery_options' ));

echo '</div>';
}
}




// Check if Gift card is in the cart

function conditional_product_in_cart( $product_id ) {
 //Check to see if user has product in cart
 global $woocommerce;

 //flag no book in cart
 $book_in_cart = false;

 foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
 $_product = $values['data'];

 if ( $_product->id === $product_id ) {
 //book is in cart!
 $book_in_cart = true;

 }
 }

 return $book_in_cart;

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.