// Add custom field to checkout
add_filter( 'woocommerce_checkout_fields', 'conditional_checkout_fields_products' );
function conditional_checkout_fields_products( $fields ) {
$is_in_cart = 'nothing';
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['data']->get_id() == 4703 ) { //standard offering
$is_in_cart = 'standard';
break;
}
if ( $cart_item['data']->get_id() == 4813 ) { //iata offering
$is_in_cart = 'iata';
break;
}
}
//add field based on product in cart
if ( $is_in_cart == 'standard' ) {
$fields['billing']['merchant_id'] = array(
'label' => __('<strong>Merchant ID:</strong><br>Please enter the Merchant ID provided to you by your merchant service provider company. If you do not know your Merchant ID, you can create one by entering a series of numbers (Must be between 6 and 16 numbers long). This number will help our support team to locate your account should you need technical assistance in the future. We suggest using a number that will be easy to remember.', 'woocommerce'),
'placeholder' => _x('', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
if ( $is_in_cart == 'iata' ) {
$fields['billing']['iata_id'] = array(
'label' => __('Enter your 8-digit numeric code, assigned by IATA', 'woocommerce'),
'placeholder' => _x('', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
return $fields;
}
//save the custom field data
function save_extra_checkout_fields( $order_id, $posted ){
// don't forget appropriate sanitization if you are using a different field type
if ( ! empty( $_POST['merchant_id'] ) ) {
update_post_meta( $order_id, 'merchant_id', sanitize_text_field( $posted['merchant_id'] ) );
}
if ( ! empty( $_POST['iata_id'] ) ) {
update_post_meta( $order_id, 'iata_id', $posted['iata_id'] );
}
}
add_action( 'woocommerce_checkout_update_order_meta', 'save_extra_checkout_fields', 10, 2 );
// Add Custom field to admin order data
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
//do we have merchant id or iata id?
if(get_post_meta( $order->get_id(), 'merchant_id', true )){
echo '<p><strong>'.__('Merchant ID').':</strong> <br/>' . get_post_meta( $order->get_id(), 'merchant_id', true ) . '</p>';
}
if(get_post_meta( $order->get_id(), 'iata_id', true )){
echo '<p><strong>'.__('IATA ID').':</strong> <br/>' . get_post_meta( $order->get_id(), 'iata_id', true ) . '</p>';
}
}