Show custom billing checkout fields by product id

A very important snippet that you can use to show custom billing checkout fields by product id

add_action( 'woocommerce_checkout_fields', 'hqhowdotcom_cutom_checkout_field_conditional_logic' );
function hqhowdotcom_cutom_checkout_field_conditional_logic( $fields ) {
foreach( WC()->cart->get_cart() as $cart_item ){
     $product_id = $cart_item['product_id'];
//change 2020 to your product id
   if( $product_id == 2020 ) {
    $fields['billing']['billing_field_' . $product_id] = array(
     'label'     => __('Custom Field on Checkout for ' . $product_id, 'woocommerce'),
     'placeholder'   => _x('Custom Field on Checkout for ' . $product_id, 'placeholder', 'woocommerce'),
     'required'  => false,
     'class'     => array('form-row-wide'),
     'clear'     => true
    );
   }
}
// Return checkout fields.
 return $fields;
}

Leave a Reply

Your email address will not be published. Required fields are marked *