php - Auto update Wordpress user data when editing their order details in Woocommerce
Get the solution ↓↓↓Solution:
Yes this can be done using save_post_shop_order
hook for all billing and shipping customer fields (including "billing email" and "billing phone" fields):
add_action('save_post_shop_order', 'update_wp_user_data', 50, 3 );
function update_wp_user_data( $post_id, $post, $update ) {
// Checking that is not an autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
update_post_meta( $post_id, '_invoices_files', 'auto-save-verif' );
return $post_id;
}
// Check the user’s permissions (for 'shop_manager' and 'administrator' user roles)
if ( ! current_user_can( 'edit_shop_order', $post_id ) ){
update_post_meta( $post_id, '_invoices_files', 'user-roles-verif' );
return $post_id;
}
// Get the customer ID and check if it's valid
$customer_id = get_post_meta( $post_id, '_customer_user', true );
if( empty($customer_id) || $customer_id == 0 )
return $post_id;
// Set all field keys in arrays
$field_keys = array('first_name', 'last_name', 'company', 'address_1', 'address_2', 'city',
'postcode', 'country', 'state');
$fields_keys2 = array('email', 'phone');
foreach( $field_keys as $key ){
if( isset($_POST['_billing_'.$key]) ){
update_user_meta( $customer_id, 'billing_'.$key, sanitize_text_field( $_POST['_billing_'.$key] ) );
}
if( isset($_POST['_shipping_'.$key]) ){
update_user_meta( $customer_id, 'shipping_'.$key, sanitize_text_field( $_POST['_shipping_'.$key] ) );
}
}
foreach( $fields_keys2 as $key ){
if( isset($_POST['_billing_'.$key]) ){
update_user_meta( $customer_id, 'billing_'.$key, sanitize_text_field( $_POST['_billing_'.$key] ) );
}
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and work.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: git was not found in your path, skipping source download
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.