67
We’ve already seen how to update user meta after a successful order, but this time our goal is to “correct” or “edit” a checkout field value after the order is placed.
You could for example add a phone number prefix if it’s not there, and by doing so, correct the phone number before sending it to your courier. Likewise, you could remove punctuation, trim spaces, format accents, and do any manipulation you desire on whatever order field.
So, here’s how they do it. Enjoy!
PHP Snippet: Alter Order Field Value After An Order is Placed @ WooCommerce Checkout
In this example, we’ll see how to re-format the phone number entered during checkout, by adding a prefix if it’s not there. Also, you’ll learn about the handy get_country_calling_code() WooCommerce function, which is good to know!
/**
* @snippet Update Order Meta After a Successful Order - WooCommerce
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible WooCommerce 4.6
* @donate $9 https://tutoraspire.com
*/
add_action( 'woocommerce_thankyou', 'tutoraspire_alter_checkout_fields_after_order' );
function tutoraspire_alter_checkout_fields_after_order( $order_id ) {
$order = wc_get_order( $order_id );
$phone = $order->get_billing_phone();
$calling_code = WC()->countries->get_country_calling_code( $order->get_billing_country() );
$calling_code = is_array( $calling_code ) ? $calling_code[0] : $calling_code;
if ( $phone && $calling_code && ! str_starts_with( $phone, $calling_code ) ) {
// str_starts_with() works on PHP 8+ only
$phone = $calling_code . $phone;
update_post_meta( $order_id, '_billing_phone', $phone );
}
}