Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add custom fields in user registration on the "My Account" page #7667

Closed
crespopantaleon opened this issue Mar 8, 2015 · 7 comments
Closed
Assignees

Comments

@crespopantaleon
Copy link

Hi, first sorry for my english (I'm using a translator).

I used this code in my store (https://support.woothemes.com/hc/en-us/articles/203182373) by @claudiosmweb Following this thread (#6007) I've implemented via a plugin like also explains @claudiosmweb

I have problems with some things and would be very grateful if you could help me.

I added several fields: first name, last name, phone, address 1, city, postcode, state (in Spain are provinces) ...

The main problem I have with the state field. Reviewing the fields of the database with two test users (a user registered through the registration form at "My account" page and other users registered through "Checkout" page) differences appear in the records of the database.

Firstly, it seems that all is well, the state code field is equal for the two users, but in the "My Account" information about the address is different. Also, for a user His name appears after "Hello, xxx ..." and other shows His email "Hello, email ..."

On the other hand, for the registered "Checkout" user also additional fields are created in the database (country, company, billing email ...)

Enclosed in this message code and screenshots.

I suppose that the problem I have when I save the extra fields when the user is created (sanitaze_text_field in the state field ???) and I guess I have not created correctly the state selector ( select2 ???). But it's what I think, I'll probably wrong. I'm not a developer, so these problems. Thank you very much for your time and I hope your help

@crespopantaleon
Copy link
Author

Here is the code:

<?php
/**
 * Plugin Name: WooCommerce Registration Fields
 * Description: My Custom registration fields.
 * Version: 1.0
 * Author: Antonio Crespo
 * License: GPL2
 */

/* Extra Fields in WooCommerce Registration */

/**
 * Add new register fields for WooCommerce registration.
 *
 * @return string Register fields HTML.
 */
function wooc_extra_register_fields() {
    ?>

    <p class="form-row form-row-wide">
    <label for="reg_billing_first_name"><?php _e( 'Nombre', 'woocommerce' ); ?> <span class="required">*</span></label>
    <input type="text" class="input-text" name="billing_first_name" id="reg_billing_first_name" value="<?php if ( ! empty( $_POST['billing_first_name'] ) ) esc_attr_e( $_POST['billing_first_name'] ); ?>" />
    </p>

    <p class="form-row form-row-wide">
    <label for="reg_billing_last_name"><?php _e( 'Apellidos', 'woocommerce' ); ?> <span class="required">*</span></label>
    <input type="text" class="input-text" name="billing_last_name" id="reg_billing_last_name" value="<?php if ( ! empty( $_POST['billing_last_name'] ) ) esc_attr_e( $_POST['billing_last_name'] ); ?>" />
    </p>

    <p class="form-row form-row-wide">
    <label for="reg_billing_phone"><?php _e( 'Teléfono', 'woocommerce' ); ?> <span class="required">*</span></label>
    <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="<?php if ( ! empty( $_POST['billing_phone'] ) ) esc_attr_e( $_POST['billing_phone'] ); ?>" />
    </p>

    <p class="form-row form-row-wide">
    <label for="reg_billing_address_1"><?php _e( 'Dirección', 'woocommerce' ); ?> <span class="required">*</span></label>
    <input type="text" class="input-text" name="billing_address_1" id="reg_billing_address_1" value="<?php if ( ! empty( $_POST['billing_address_1'] ) ) esc_attr_e( $_POST['billing_address_1'] ); ?>" />
    </p>

    <p class="form-row form-row-wide">
    <label for="reg_billing_postcode"><?php _e( 'Código Postal / Zip', 'woocommerce' ); ?> <span class="required">*</span></label>
    <input type="text" class="input-text" name="billing_postcode" id="reg_billing_postcode" value="<?php if ( ! empty( $_POST['billing_postcode'] ) ) esc_attr_e( $_POST['billing_postcode'] ); ?>" />
    </p>

    <p class="form-row form-row-wide">
    <label for="reg_billing_city"><?php _e( 'Localidad / Ciudad', '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'] ); ?>" />
    </p>

    <p class="form-row form-row-wide">
    <label for="reg_billing_state"><?php _e( 'Provincia', 'woocommerce' ); ?> <span class="required">*</span></label>
    <select class="state_select" name="billing_state" id="reg_billing_state">
    <option value="">Selecciona una província&hellip;</option><option value="C" >A Coru&ntilde;a</option><option value="VI" >Álava</option><option value="AB" >Albacete</option><option value="A" >Alicante</option><option value="AL" >Almería</option><option value="O" >Asturias</option><option value="AV" >Ávila</option><option value="BA" >Badajoz</option><option value="PM" >Baleares</option><option value="B" >Barcelona</option><option value="BU" >Burgos</option><option value="CC" >Cáceres</option><option value="CA" >Cádiz</option><option value="S" >Cantabria</option><option value="CS" >Castellón</option><option value="CE" >Ceuta</option><option value="CR" >Ciudad Real</option><option value="CO">Córdoba</option><option value="CU" >Cuenca</option><option value="GI" >Gerona</option><option value="GR" >Granada</option><option value="GU" >Guadalajara</option><option value="SS" >Guipúzcoa</option><option value="H" >Huelva</option><option value="HU" >Huesca</option><option value="J" >Jaén</option><option value="LO" >La Rioja</option><option value="GC" >Las Palmas</option><option value="LE" >León</option><option value="L" >Lérida</option><option value="LU" >Lugo</option><option value="M" >Madrid</option><option value="MA" >Málaga</option><option value="ML" >Melilla</option><option value="MU" >Murcia</option><option value="NA" >Navarra</option><option value="OR" >Orense</option><option value="P" >Palencia</option><option value="PO" >Pontevedra</option><option value="SA" >Salamanca</option><option value="TF" >Santa Cruz de Tenerife</option><option value="SG" >Segovia</option><option value="SE" >Sevilla</option><option value="SO" >Soria</option><option value="T" >Tarragona</option><option value="TE" >Teruel</option><option value="TO" >Toledo</option><option value="V" >Valencia</option><option value="VA" >Valladolid</option><option value="BI" >Vizcaya</option><option value="ZA" >Zamora</option><option value="Z" >Zaragoza</option>
    </select>
    </p>

    <?php
}

add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );

/**
 * Validate the extra register fields.
 *
 * @param  string $username          Current username.
 * @param  string $email             Current email.
 * @param  object $validation_errors WP_Error object.
 *
 * @return void
 */
function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) {
    if ( isset( $_POST['billing_first_name'] ) && empty( $_POST['billing_first_name'] ) ) {
        $validation_errors->add( 'billing_first_name_error', __( 'Nombre es un campo requerido.', 'woocommerce' ) );
    }

    if ( isset( $_POST['billing_last_name'] ) && empty( $_POST['billing_last_name'] ) ) {
        $validation_errors->add( 'billing_last_name_error', __( 'Apellidos es un campo requerido.', 'woocommerce' ) );
    }


    if ( isset( $_POST['billing_phone'] ) && empty( $_POST['billing_phone'] ) ) {
        $validation_errors->add( 'billing_phone_error', __( 'Teléfono es un campo requerido.', 'woocommerce' ) );
    }

    if ( isset( $_POST['billing_address_1'] ) && empty( $_POST['billing_address_1'] ) ) {
        $validation_errors->add( 'billing_address_1_error', __( 'Dirección es un campo requerido.', 'woocommerce' ) );
    }

    if ( isset( $_POST['billing_postcode'] ) && empty( $_POST['billing_postcode'] ) ) {
        $validation_errors->add( 'billing_postcode_error', __( 'Código postal / Zip es un campo requerido.', 'woocommerce' ) );
    }

    if ( isset( $_POST['billing_city'] ) && empty( $_POST['billing_city'] ) ) {
        $validation_errors->add( 'billing_city_error', __( 'Localidad / Ciudad es un campo requerido.', 'woocommerce' ) );
    }

    if ( isset( $_POST['billing_state'] ) && empty( $_POST['billing_state'] ) ) {
        $validation_errors->add( 'billing_state', __( 'Provincia es un campo requerido.', 'woocommerce' ) );
    }
}

add_action( 'woocommerce_register_post', 'wooc_validate_extra_register_fields', 10, 3 );

/**
 * Save the extra register fields.
 *
 * @param  int  $customer_id Current customer ID.
 *
 * @return void
 */
function wooc_save_extra_register_fields( $customer_id ) {
    if ( isset( $_POST['billing_first_name'] ) ) {
        // WordPress default first name field.
        update_user_meta( $customer_id, 'first_name', sanitize_text_field( $_POST['billing_first_name'] ) );

        // WooCommerce billing first name.
        update_user_meta( $customer_id, 'billing_first_name', sanitize_text_field( $_POST['billing_first_name'] ) );
    }

    if ( isset( $_POST['billing_last_name'] ) ) {
        // WordPress default last name field.
        update_user_meta( $customer_id, 'last_name', sanitize_text_field( $_POST['billing_last_name'] ) );

        // WooCommerce billing last name.
        update_user_meta( $customer_id, 'billing_last_name', sanitize_text_field( $_POST['billing_last_name'] ) );
    }

    if ( isset( $_POST['billing_phone'] ) ) {
        // WooCommerce billing phone
        update_user_meta( $customer_id, 'billing_phone', sanitize_text_field( $_POST['billing_phone'] ) );
    }

    if ( isset( $_POST['billing_address_1'] ) ) {
        // WooCommerce billing address
        update_user_meta( $customer_id, 'billing_address_1', sanitize_text_field( $_POST['billing_address_1'] ) );
    }

    if ( isset( $_POST['billing_postcode'] ) ) {
        // WooCommerce billing postcode
        update_user_meta( $customer_id, 'billing_postcode', sanitize_text_field( $_POST['billing_postcode'] ) );
    }

    if ( isset( $_POST['billing_city'] ) ) {
        // WooCommerce billing city
        update_user_meta( $customer_id, 'billing_city', sanitize_text_field( $_POST['billing_city'] ) );
    }

    if ( isset( $_POST['billing_state'] ) ) {
        // WooCommerce billing state
        update_user_meta( $customer_id, 'billing_state', sanitize_text_field( $_POST['billing_state'] ) );
    }
}

add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );

@claudiosanches
Copy link
Contributor

I tested and works fine.
To address the work you should also save the country.

Please don't use our issue tracker for support requests, but for core WooCommerce issues only. Support can take place in the appropriate channels:

@crespopantaleon
Copy link
Author

Hello Claudio, thanks for your time, I will try to register the country and check if the address shown in my account page is changed. I did not know that your issue tracker is for WooCommerce core issues only. I will write later in wordpress.org if I have other problems. bye!

@djpacmansd
Copy link

djpacmansd commented Oct 25, 2016

Hello! Thank you for the great tutorial. Would this be possible for a custom registration field that's not part of woocommerce? For example I want to add fields such as Age, License Number or License state. Is this possible using this technique and having it show up under the user's profile? Lastly, I notice in your 'wooc_save_extra_register_fields' function you used a variable for $customer_id. How are you getting that ID dynamically? Any help would be appreciated. Thanks.

@CaioBabler
Copy link

Hi, I'm having the following problem, I'm using Brazilian checkout fields I need the fields billing_cnpj and billing_ei to be required how do I? I am using the following code to get the checkout fields and use them in the register

function startsWith($haystack, $needle)
{
    return $needle === '' || strpos($haystack, $needle) === 0;
}

add_action( 'woocommerce_checkout_init', 'woocommerce_countries_states', 10, 1 );
function woocommerce_countries_states( $checkout ) {
    global $woocommerce;
    $countries_obj   = new WC_Countries();
    $countries   = $countries_obj->__get('countries');
    $default_country = $countries_obj->get_base_country();
    $default_county_states = $countries_obj->get_states( $default_country );

    $checkout->checkout_fields['account']['billing_country'] = array(
        'type'              => 'select',
        'label'             => __( 'Default Contries', 'woocommerce' ),
        'required'          => true,
        'options'    => $countries
    );

   
}

add_action( 'register_form', 'woocommerce_reg_extra', 15 );
//add_action( 'woocommerce_register_form', 'woocommerce_reg_extra');

function woocommerce_reg_extra() {
    global $woocommerce;
    $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
    $assets_path = str_replace( array( 'http:', 'https:' ), '', WC()->plugin_url() ) . '/assets/';
    $frontend_script_path = $assets_path . 'js/frontend/';
    wp_enqueue_script( 'wc-country-select', $frontend_script_path . 'country-select' . $suffix . '.js' );

    $checkout = $woocommerce->checkout();
    ?>
    <h3><?php _e( 'Informação de envio', 'woocommerce' ); ?></h3>
    <?php
    foreach ($checkout->checkout_fields['billing'] as $key => $field) :
    woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );
    endforeach;
    ?>

    <div class = "terms_checkbox">
		<input type="checkbox" name="terms_agree" value="1" />
		<a href = "http://localhost/zoomania/index.php/termos-e-condicoes/" target="_blank">Eu concordo com os termos e condições</a>
    </div>
    <?php
}

// Custom function to save Usermeta or Billing Address of registered user
function save_address($user_id)
{
    global $woocommerce;
    $address = $_POST;
    foreach ($address as $key => $field) :
    if(startsWith($key,'billing_'))
    {
    // Condition to add firstname and last name to user meta table
    if($key == 'billing_first_name' || $key == 'billing_last_name')
    {
    $new_key = explode('billing_',$key);
    update_user_meta( $user_id, $new_key[1], $_POST[$key] );
    }
    update_user_meta( $user_id, $key, $_POST[$key] );
    }
    endforeach;

}
add_action('woocommerce_created_customer','save_address', 10, 3);

// Registration page billing address form Validation

function validate_extra_wp_register_fields( $errors, $sanitized_user_login, $user_email )
{
    global $woocommerce;

    
    return $errors;
}

add_filter('registration_errors','validate_extra_wp_register_fields', 10, 3);
add_action( 'woocommerce_register_post', 'validate_extra_register_fields', 10, 3 );

function validate_extra_register_fields( $username, $validation_errors )
{

if ( empty($_POST['billing_country'])  )
{
	$validation_errors->add( 'country_error', __( '<strong>Error</strong>: Primeiro selecione um país.', 'woocommerce' ) );
}

if ( empty($_POST['billing_first_name']) )
{
	 $validation_errors->add( 'first_name_error', __( '<strong>Error</strong>: Insira o nome.', 'woocommerce' ) );
}

if ( empty($_POST['billing_last_name']) )
{
	$validation_errors->add( 'last_name_error', __( '<strong>Error</strong>: Insira o sobrenome.', 'woocommerce' ) );
}
if ( empty($_POST['billing_address_1']) )
{
	$validation_errors->add( 'address1_error', __( '<strong>Error</strong>: Introduza o endereço.', 'woocommerce' ) );
}
if ( empty($_POST['billing_city']) )
{
	$validation_errors->add( 'address2_error', __( '<strong>Error</strong>: Introduza a cidade.', 'woocommerce' ) );
}

if ( empty($_POST['billing_state'])  )
{
	$validation_errors->add( 'state_error', __( '<strong>Error</strong>: Selecione ou digite um estado.', 'woocommerce' ) );
}

if ( empty($_POST['billing_postcode'])  )
{
	$validation_errors->add( 'postcode_error', __( '<strong>Error</strong>: Por favor, entre seu cep.', 'woocommerce' ) );
}

//if ( empty($_POST['billing_email']) )
//{
	//$validation_errors->add( 'email_error', __( '<strong>Error</strong>: Insira seu e-mail.', 'woocommerce' ) );
//}
if ( empty($_POST['billing_phone'])  )
{
	$validation_errors->add( 'phone_error', __( '<strong>Error</strong>: Insira seu numero de telefone.', 'woocommerce' ) );
}
if ( empty($_POST['terms_agree'])  )
{
	$validation_errors->add( 'terms_error', __( '<strong>Error</strong>: Concorde com os nossos termos e condições para utilizar este serviço.', 'woocommerce' ) );
}

}
//esconder preço se não logado

@alexanderbiscajin
Copy link

I have been using the code to add registration form fields to WooCommerce store referring this article https://www.wpblog.com/add-registration-form-woocommerce-stores/ as it seems to be more easy and simple.

@VadalamaniBalaji
Copy link

hai my registration page i have add extra field like gender radio button,area of interest textarea, date of birth as dropdown how to add this field

@woocommerce woocommerce locked as off-topic and limited conversation to collaborators Jan 25, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants