WordPress   

Add custom field in My Account(edit-account) page of Woocommerce

In this example we will add a new custom field in the My Account page of woocommerce. We will also save this field data on form update and add custom validation to this newly added field.

Note – We will be adding tax_code as our new custom field in this example. You can change this according to your requirements like birth_date, car_number or anything else.

Step 1: Adding a new field in the My Account page

Following code snippet will add the new custom field at the end of the form. If you want to add it above all existing fields then you can use woocommerce_edit_account_form_start hook instead of woocommerce_edit_account_form in the following code snippet.

// Add a custom field in the woocommerce My Account(edit-account) page
add_action( 'woocommerce_edit_account_form', 'add_custom_field_edit_account_page_woo' );
function add_custom_field_edit_account_page_woo() {
	$user = wp_get_current_user(); 
	woocommerce_form_field( 'tax_code', array(
		'type'        => 'text',
		'class' => array('woocommerce-form-row','woocommerce-form-row--wide'), // Add your custom CSS classes here
		'required'    => true, // This will just add * after the field label
		'label'       => 'Tax Code',
	), $user->tax_code); // Pre populate the field with existing values in future
}

Step 2: Save the custom field value when the form is submitted

After adding the custom field to the form, we need to save it’s data when the form is submitted. This can be easily done with the help of woocommerce_save_account_details hook.

//Save newly added custom field when the form is updated
add_action( 'woocommerce_save_account_details', 'save_custom_field_account_details_page_woo', 12, 1 );
function save_custom_field_account_details_page_woo( $user_id ) {
    if(isset( $_POST['tax_code'])){
        update_user_meta( $user_id, 'tax_code', sanitize_text_field( $_POST['tax_code'] ) );
    }
}

Step 3: Add validation to the custom field

We can make our newly added custom field required or add any custom validations according our requirements. For this we can use woocommerce_save_account_details_errors WordPress hook to add our custom validation function. If you don’t want to add any type of validation to the new custom field then you can skip this step.

//Add validation to the fields on woocommerce My Account(edit-account) page
add_action( 'woocommerce_save_account_details_errors','validate_edit_account_custom_field', 10, 1 );
function validate_edit_account_custom_field( $errors ){
    if (isset( $_POST['tax_code']) && empty($_POST['tax_code']) ){
        $errors->add( 'error', __( 'Tax Code is a required field', 'woocommerce' ),'');
    }
}
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us