I'm struggling with my custom registration fields for WooCommerce. I need 2 registration fields.
- B2B
- B2C
So I was thinking to create two registration pages, one for B2B and one for B2C.
I created the pages, added the code and registered the new fields in the database. This works all fine, but not for 1 field. It's a dropdown field for choosing the country.
The code below is a normal input. This field is registered in the database at registration and de value is added to the WooCommerce account page from the registered user.
<div class="col-md-12">
<label for="reg_billing_city"><?php _e( 'City', 'woocommerce' ); ?><span class="required">*</span></label>
<input type="text" class="input-text" name="billing_city" id="reg_billing_city" value="<?php if ( ! empty( $_POST['billing_city'] ) ) esc_attr_e( $_POST['billing_city'] ); ?>" />
</div>
I also need the country of the registered user at the account page. I'm using the code below:
<div class="col-md-12">
<label for="reg_billing_country"><?php _e( 'Country', 'woocommerce' ); ?><span class="required">*</span></label>
<select class="input-text" name="billing_country" id="reg_billing_country" value="<?php if ( ! empty( $_POST['billing_country'] ) ) esc_attr_e( $_POST['billing_country'] ); ?>">
<option value="Nederland">Nederland</option>
<option value="Belgie">Belgie</option>
<option value="Duitsland">Duitsland</option>
<option value="Frankrijk">Frankrijk</option>
</select>
</div>
But the value from billing_country is not added to the customs account page.
if ( isset( $_POST['billing_country'] ) ) {
update_user_meta( $customer_id, 'billing_country', sanitize_text_field( $_POST['billing_country'] ) );
}
So how to get the value of the dropdown updated to the user metadata?
There are some mistakes in your code for the billing country field:
<option value="{$country_code}">.value=""in the<select>itself, instead you need to set for the corresponding selected option value, the attributeselected.Here is the complete code, displaying the fields, validating and saving:
Code goes in functions.php file of your child theme (or in a plugin). It should work.
Addition
Add "Account type" dropdown to registration form start
Instead of using 2 registration forms, you could add a dropdown for the "Account type" in the registration form start, like:
Then you will add into the validation function:
And in the saving function:
To finish, if you need to show / hide some fields depending on the selected account type value, you can use JavaScript / jQuery…