Overview
In a recent tutorial I explained how one can add custom fields to the WooCommerce checkout. However, adding custom fields to the checkout don’t fully enable them in the admin user profile area or the user’s profile page. The custom fields will probably show up in the user’s profile pages but any modifications to them won’t be registered. We need to write a few lines of code to achieve this.
In the image below, we have several custom checkout fields like – Prefix, Address Line 3, Spouse Name, Concert seats, Options to receive emails, Options to receive hard-copies of newsletters etc.
Note: I am using a membership plugin Paid Memberships Pro with WooCommerce in the image below.
Any changes from the Admin area should reflect in the user’s profile, and vice-versa.
Profile page when a User is editing their own profile
Profile page when a special user or Admin is editing a user’s profile from the Dashboard
Saving custom woocommerce checkout fields in the User’s profile pages
We need to make use of two action_hooks to achieve this:
- personal_options_update – (action only fires if the current user is editing their own profile)
- edit_user_profile_update – (action can be used for backend user editing)
I am adding all my woocommerce customizations to a file woocommerce-customizations.php. See this post on how I make my customizations to woocommerce without bloating functions.php.
In your woocommerce customizations.php (or functions.php) add the following:
add_action( 'personal_options_update', 'custom_save_custom_profile_fields' ); add_action( 'edit_user_profile_update', 'custom_save_custom_profile_fields' ); function custom_save_custom_profile_fields( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; if (isset($_POST['field_name'])) { update_usermeta( $user_id, 'field_name', wc_clean($_POST['field_name']) ); } //repeat for other custom fields }
You will have to check for all the custom fields in the $_POST variable. If the value has been set or updated, it will also be saved with the user meta.
Leave a Reply