• Никакой политики на форуме. Иначе - бан!
  • Вопрос без рабочей ссылки на проблему считается риторическим. Без ссылки и скриншота - провокацией!
  • Темы озаглавленные с маленькой буквы или капсом удаляются без предупреждения!

Как добавить кастомные поля на странице регистрации?

Agas007

Новичок
Есть задача сделать индивидуальную форму для регистрации клиента.
Сейчас при регистрации есть 2 поля Email и Пароль.
Мне нужно добавить еще 6 полей:
Фамилия, Имя, Отчество, Город, Контактный телефон, Подтверждение пароля.

Я нашел в папке "plagin" страницу form-login.php , поменял её под себя, она вывелась на странице регистрации.
Сейчас проблема заключается в том, как проверять и получать данные из этих полей при регистрации, и передавать их в админку при этом создавая эти дополнительные поля в админке, что бы их мог просматривать админ и в дальнейшем они использовались при составлении заказа.
 

Вложения

  • сейчас регистрация.jpg
    сейчас регистрация.jpg
    52.5 KB · Просмотры: 7
  • Нужно сделать.jpg
    Нужно сделать.jpg
    20.7 KB · Просмотры: 7

rudolfl

Новичок
Я недавно как раз делал. Кидаю свой код -- подправьте как вам надо.

1. Добавить сами поля:
PHP:
/* Add additional fields to registration */
function rl_extra_register_fields() {?>
           <p class="form-row form-row-first">
           <label for="reg_billing_first_name"><?php _e( 'First name', '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-last">
           <label for="reg_billing_last_name"><?php _e( 'Last name', '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 class="form-row form-row-wide">
           <label for="reg_billing_company"><?php _e( 'Business Name', 'woocommerce' ); ?><span class="required">*</span></label>
           <input type="text" class="input-text" name="billing_company" id="reg_billing_company" value="<?php if ( ! empty( $_POST['billing_company'] ) ) esc_attr_e( $_POST['billing_company'] ); ?>" />
           </p>
           <p class="form-row form-row-wide">
           <label for="reg_billing_phone"><?php _e( 'Phone', '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_city"><?php _e( 'City/Suburb', '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_postcode"><?php _e( 'Postcode/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>
<?php
    wp_enqueue_script( 'wc-country-select' );

    woocommerce_form_field( 'billing_country', array(
        'type'      => 'country',
        //'class'     => array('chzn-drop'),
        'label'     => __('Country'),
        'placeholder' => __('Choose your country.'),
        'required'  => true,
        //'clear'     => true
    ),'AU');

?>
           </p>
           <div class="clear"></div>
<?php
     }
add_action( 'woocommerce_register_form_start', 'rl_extra_register_fields' );

2. Так как WooCommerce о ваших полях понятия не имеет, надо их проверять самому:

PHP:
/* Validate user input on registration form */
function rl_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',__('A first name is required!','woocommerce'));}
    if(isset($_POST['billing_last_name']) && empty($_POST['billing_last_name'])){$validation_errors->add('billing_last_name_error',__('A last name is required!','woocommerce'));}
    if(isset($_POST['billing_company']) && empty($_POST['billing_company'])){$validation_errors->add('billing_company_error',__('A Business Name is required!','woocommerce'));}
    if(isset($_POST['billing_country']) && empty($_POST['billing_country'])){$validation_errors->add('billing_country_error',__('A country is required!','woocommerce'));}
    if(isset($_POST['billing_city']) && empty($_POST['billing_city'])){$validation_errors->add('billing_city_error',__('A city is required!','woocommerce'));}
    if(isset($_POST['billing_postcode']) && empty($_POST['billing_postcode'])){$validation_errors->add('billing_postcode_error',__('A postcode is required!','woocommerce'));}
    if(isset($_POST['billing_phone']) && empty($_POST['billing_phone'])){$validation_errors->add('billing_phone_error',__('A phone number is required!','woocommerce'));}
    return $validation_errors;
}
add_action('woocommerce_register_post','rl_validate_extra_register_fields',10,3);

3, Ну, и наконец, надо их сохранить.

Тут у меня небольшая ж..а получилась, Работало до последнего апдейта WordPress. Теперь у них какая-то проблема, но решаемая.

Вначале сохранял так:
PHP:
function rl_save_extra_register_fields($customer_id){
    if(isset($_POST['billing_first_name'])){
        update_user_meta($customer_id,'first_name',sanitize_text_field($_POST['billing_first_name']));
        update_user_meta($customer_id,'billing_first_name',sanitize_text_field($_POST['billing_first_name']));
    }
    if(isset($_POST['billing_last_name'])){
        update_user_meta($customer_id,'last_name',sanitize_text_field($_POST['billing_last_name']));
        update_user_meta($customer_id,'billing_last_name',sanitize_text_field($_POST['billing_last_name']));
    }
    if(isset($_POST['billing_company'])){
        update_user_meta($customer_id,'billing_company',sanitize_text_field($_POST['billing_company']));
    }
    if(isset($_POST['billing_country'])){
        update_user_meta($customer_id,'billing_country',sanitize_text_field($_POST['billing_country']));
    }
    if(isset($_POST['billing_city'])){
        update_user_meta($customer_id,'billing_city',sanitize_text_field($_POST['billing_city']));
    }
    if(isset($_POST['billing_postcode'])){
        update_user_meta($customer_id,'billing_postcode',sanitize_text_field($_POST['billing_postcode']));
    }
    if(isset($_POST['billing_state'])){
        update_user_meta($customer_id,'billing_state',sanitize_text_field($_POST['billing_state']));
    }
    if(isset($_POST['billing_phone'])){
        update_user_meta($customer_id,'billing_phone',sanitize_text_field($_POST['billing_phone']));
    }
    if(isset($_POST['email'])){
        update_user_meta($customer_id,'billing_email',sanitize_text_field($_POST['email']));
    }

}
add_action('woocommerce_created_customer','rl_save_extra_register_fields');

update_user_meta() создаёт поле само если не находит.

Почему-то код перестал работать -- сохраняет только некоторые поля! Попробуйте, что у вас получится.

В моём случае мне пришлос; дублировать сохранение так:
Код:
function rl_new_customer_role($args)
{
        $args['role'] = 'customer_pending';
        error_log(var_export($_POST,true));

    if(isset($_POST['billing_first_name'])){
        $args['first_name'] = sanitize_text_field($_POST['billing_first_name']);
        $args['billing_first_name'] = sanitize_text_field($_POST['billing_first_name']);
    }
    if(isset($_POST['billing_last_name'])){
        $args['last_name'] = sanitize_text_field($_POST['billing_last_name']);
        $args['billing_last_name'] = sanitize_text_field($_POST['billing_last_name']);
    }
    if(isset($_POST['billing_company'])){
        $args['billing_company'] = sanitize_text_field($_POST['billing_company']);
    }
    if(isset($_POST['billing_country'])){
        $args['billing_country'] = sanitize_text_field($_POST['billing_country']);
    }
    if(isset($_POST['billing_city'])){
        $args['billing_city'] = sanitize_text_field($_POST['billing_city']);
    }
    if(isset($_POST['billing_postcode'])){
        $args['billing_postcode'] = sanitize_text_field($_POST['billing_postcode']);
    }
    if(isset($_POST['billing_state'])){
        $args['billing_state'] = sanitize_text_field($_POST['billing_state']);
    }
    if(isset($_POST['billing_phone'])){
        $args['billing_phone'] = sanitize_text_field($_POST['billing_phone']);
    }
    if(isset($_POST['email'])){
        $args['billing_email'] = sanitize_text_field($_POST['email']);
    }

        return $args;
}
add_filter('woocommerce_new_customer_data', 'rl_new_customer_role');

В этом фильтре сохранялись остальные поля. Половина в одной функции, половина в другой. Так и не нашёл причины пока.

Rudolf
 
Сверху Снизу