Skip to content

Instantly share code, notes, and snippets.

@wplaunchify
Forked from corsonr/functions.php
Created February 24, 2020 05:52
Show Gist options
  • Save wplaunchify/080a4e3b19e7b7286b1a4973b0a7c64a to your computer and use it in GitHub Desktop.
Save wplaunchify/080a4e3b19e7b7286b1a4973b0a7c64a to your computer and use it in GitHub Desktop.
WooCommerce: Add conditional checkout fields based on products in cart
<?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