I have the following code which adds a custom field to checkout for a specific product, adds it to the new order page and send’s it in the new order email.
add_action( 'woocommerce_after_checkout_billing_form', 'my_custom_checkout_field', 10, 1 );
function my_custom_checkout_field( $checkout ) {
$targeted_product_id = 6270; //Global Membership ID
foreach( WC()->cart->get_cart() as $item ){
if ( ! in_array($targeted_product_id, [$item['product_id'], $item['variation_id']]) ) {
return; // Exit if there are other products in cart that the targeted one.
}
}
echo '<div id="my_custom_checkout_field">
<h2>' . __('Please select your Delivery Partner') . '</h2>';
woocommerce_form_field( 'delivery_partner', array(
'type' => 'select',
'required' => 'true',
'options' => array(
'---Please select your Delivery Partner' => __('---Please select your Delivery Partner', 'woocommerce' ),
'Learners University College (LUC), Dubai' => __('Learners University College (LUC), Dubai', 'woocommerce' ),
'Elite Training Services (ECS), KSA' => __('Elite Training Services (ECS), KSA ', 'woocommerce' ),
'MELI, KSA' => __('MELI, KSA', 'woocommerce' ),
'KLD Management Training, Dubai' => __('KLD Management Training, Dubai', 'woocommerce' )),
'class' => array('my-field-class form-row-wide'),
'label' => __('Delivery Partner'),
), $checkout->get_value( 'delivery_partner' ));
echo '</div>';
}
// Save the dropdown custom field selected value as order custom meta data:
add_action( 'woocommerce_checkout_create_order', 'my_custom_checkout_field_update_order_meta', 10, 2 );
function my_custom_checkout_field_update_order_meta( $order, $data ) {
if ( isset($_POST['delivery_partner']) && ! empty($_POST['delivery_partner']) ) {
$order->update_meta_data( 'Delivery Partner', sanitize_text_field( $_POST['delivery_partner'] ) );
}
}
// Display the custom field value on admin order pages after billing adress:
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 ) {
echo '<p><strong>'.__('Delivery Partner').':</strong> ' . $order->get_meta('Delivery Partner') . '</p>';
}
// Display the custom field value on "New Order" notification:
add_action( 'woocommerce_email_after_order_table', 'custom_woocommerce_email_order_meta_fields', 10, 4 );
function custom_woocommerce_email_order_meta_fields( $order, $sent_to_admin, $plain_text, $email ) {
if( 'new_order' === $email->id )
echo '<p><strong>'.__('delivery_partner').':</strong> ' . $order->get_meta('Delivery Partner') . '</p>';
}
What I need is to add it to the “Thank you for your order” page after payment is made as its currently not working.