Carl V Carl V - 1 year ago 122
PHP Question

Woocommerce Variable Checkout Fields base on Variable ID

The code below is checking to see if product ID 117 is in the cart. If it is, then it showing additional checkout fields.

I'm trying to figure out how to convert this code so instead of checking for product ids it checks for variable ids. I have two products with 2 variables each. The variable IDs that I want the form fields to be visible on are 7509 and 7529. I've tried everything that I can think of and can't seem to make these fields populate when those variables are selected.

This code was found at

* Add the field to the checkout
add_action( 'woocommerce_after_order_notes', 'wordimpress_custom_checkout_field' );

function wordimpress_custom_checkout_field( $checkout ) {

//Check if Book in Cart (UPDATE WITH YOUR PRODUCT ID)
$book_in_cart = wordimpress_is_conditional_product_in_cart( 117 );

//Book is in cart so show additional fields
if ( $book_in_cart === true ) {
echo '<div id="my_custom_checkout_field"><h3>' . __( 'Book Customization' ) . '</h3><p style="margin: 0 0 8px;">Would you like an inscription from the author in your book?</p>';

woocommerce_form_field( 'inscription_checkbox', array(
'type' => 'checkbox',
'class' => array( 'inscription-checkbox form-row-wide' ),
'label' => __( 'Yes' ),
), $checkout->get_value( 'inscription_checkbox' ) );

woocommerce_form_field( 'inscription_textbox', array(
'type' => 'text',
'class' => array( 'inscription-text form-row-wide' ),
'label' => __( 'To whom should the inscription be made?' ),
), $checkout->get_value( 'inscription_textbox' ) );

echo '</div>';


* Check if Conditional Product is In cart
* @param $product_id
* @return bool
function wordimpress_is_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;


I'd appreciate any help that can be given. Thank you in advance.

Answer Source

All the required data is stored in the cart, change

if ( $_product->id === $product_id ) {


if ( $_product->variation_id === $product_id ) {

To check multiple variation_id's pass them as an array, the following as you've tried earlier will not work, as it sends 1 (true) to the calling function.

wordimpress_is_conditional_product_in_cart(7509 || 7529) // This is incorrect, see @Howlin's answer for the correct way

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download