Created
July 13, 2018 09:06
-
-
Save corsonr/599261be409c98b01083b9aa5f81c628 to your computer and use it in GitHub Desktop.
WooCommerce: Add conditional checkout fields based on products in cart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // Do not include this if already open! Code goes in theme functions.php. | |
/** | |
* Add fields to the checkout page based on products in cart. | |
* | |
* @how-to https://remicorson.com/?p=7871 | |
* @author Remi Corson | |
* @testedwith WooCommerce 3.4.0 | |
*/ | |
add_action( 'woocommerce_checkout_fields', 'woo_add_conditional_checkout_fields' ); | |
function woo_add_conditional_checkout_fields( $fields ) { | |
foreach( WC()->cart->get_cart() as $cart_item ){ | |
$product_id = $cart_item['product_id']; | |
if( $product_id == 2009 ) { | |
$fields['billing']['billing_field_' . $product_id] = array( | |
'label' => __('Field for Product ' . $product_id, 'woocommerce'), | |
'placeholder' => _x('Field for Product ' . $product_id, 'placeholder', 'woocommerce'), | |
'required' => false, | |
'class' => array('form-row-wide'), | |
'clear' => true | |
); | |
} | |
if( $product_id == 2010 ) { | |
$fields['billing']['billing_field_' . $product_id] = array( | |
'label' => __('Field for Product ' . $product_id, 'woocommerce'), | |
'placeholder' => _x('Field for Product ' . $product_id, 'placeholder', 'woocommerce'), | |
'required' => false, | |
'class' => array('form-row-wide'), | |
'clear' => true | |
); | |
} | |
} | |
// Return checkout fields. | |
return $fields; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can I add extra input fields in array under same condition?