programing

WooCommerce 국가 등록 시 선택

css3 2023. 10. 17. 20:29

WooCommerce 국가 등록 시 선택

현재 WooCommerce의 기본 국가 검색기를 등록 페이지에 추가하려고 하는데, 기본 국가 목록은 다음 코드 스니펫으로 가능합니다.

<?php
$countries_obj  = new WC_Countries();
$countries      = $countries_obj->get_allowed_countries();
woocommerce_form_field('billing_country',array(
'type'      => 'select',
'class'     => array('chzn-drop'),
'label'     => __('Country'),
'placeholder' => __('Choose your country.'),
'options'   => $countries,
'required'  => true,
'clear'     => true
));
?>

WooCommerce에서 선택한 원래 국가와는 당연히 다르므로 등록 페이지에 이 국가 선택 필드를 추가하는 올바른 방법을 아는 사람이 있는지 궁금합니다.

편집: 내가 올바르게 이해했다면 드롭다운이 제대로 작동하려면 자바스크립트 라이브러리를 로드해야 합니다. 등록 페이지에 이를 정확히 로드하는 방법과 기본 국가를 예를 들어 '벨기에'로 설정하는 방법은 무엇입니까?

편집2: 국가 선택기 스크립트의 이 부분과 관련이 있는 것 같습니다.

<script type='text/javascript' src='//uklederwaren.be/wp-content/plugins/woocommerce/assets/js/frontend/country-select.min.js?ver=2.6.14'></script>

이것을 정확히 등록 페이지에 추가하는 방법이 확실하지 않습니다. 허용된 국가의 루프와 관련이 있다고 확신하기 때문에 어떤 도움이라도 주시면 감사하겠습니다!

편집3: 기본 국가를 어떻게 설정할 수 있는지에 대한 추가 질문 중 하나의 답변을 찾았습니다. 이는 wocommerce_form_field 배열에서 'default' => 'XX'를 추가하면 가능합니다.XX는 국가 코드를 의미하므로 벨기에의 경우에는 BE일 것입니다.

더 많은 정보를 주셔서 미리 감사드립니다.

TL;DR: enter image description here

결론:헬가의 도움으로 문제가 해결되었습니다.Vviking and Raunak Gupta는 현재 모든 섹션(및 사용자 정의 부가세 페이지)을 포함한 전체 등록 페이지에 대한 전체 코드가 다음과 같습니다.

/* ---------------------- Registration page ----------------------- */
//Add extra fields in registration form
add_action('woocommerce_register_form_start','my_extra_register_fields');
function my_extra_register_fields(){
?>
    <p class="woocommerce-FormRow 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="woocommerce-FormRow 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>
    <div class="clearfix"></div>
    <p class="woocommerce-FormRow woocommerce-FormRow--wide form-row form-row-wide">
        <label for="reg_billing_company"><?php _e('Company 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>
    <div class="clearfix"></div>
    <p class="woocommerce-FormRow woocommerce-FormRow--wide form-row form-row-wide">
        <label for="reg_billing_vat"><?php _e('VAT Number','woocommerce'); ?><span class="required">*</span></label>
        <input type="text" class="input-text" name="billing_vat" id="reg_billing_vat" value="<?php if(! empty($_POST['billing_vat'])) esc_attr_e($_POST['billing_vat']); ?>" maxlength="15" placeholder="Enter VAT Number"/>
    </p>
    <div class="clearfix"></div>
<?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,
        'default'     => 'BE'
    ));
?>
    <p class="woocommerce-FormRow form-row form-row-first">
        <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>
    <p class="woocommerce-FormRow form-row form-row-last">
        <label for="reg_billing_city"><?php _e('Town / 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']); ?>"/>
    </p>
    <div class="clearfix"></div>
    <p class="woocommerce-FormRow woocommerce-FormRow--wide form-row form-row-wide">
        <label for="reg_billing_address_1"><?php _e('Address','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']); ?>" placeholder="Street address"/>
    </p>
    <p class="woocommerce-FormRow woocommerce-FormRow--wide form-row form-row-wide">
        <input type="text" class="input-text" name="billing_address_2" id="reg_billing_address_2" value="<?php if(! empty($_POST['billing_address_2'])) esc_attr_e($_POST['billing_address_2']); ?>" placeholder="Apartment,suite,unit etc. (optional)"/>
    </p>
    <div class="clearfix"></div>
    <p class="woocommerce-FormRow woocommerce-FormRow--wide 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>
    <div class="clearfix"></div>
<?php
}
//Registration form fields Validation
add_action('woocommerce_register_post','my_validate_extra_register_fields',10,3);
function my_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 Company name is required!','woocommerce'));}
    if(isset($_POST['billing_vat']) && empty($_POST['billing_vat'])){$validation_errors->add('billing_vat_error',__('VAT number 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_state']) && empty($_POST['billing_state'])){$validation_errors->add('billing_state_error',__('A state is required!','woocommerce'));}
    if(isset($_POST['billing_address_1']) && empty($_POST['billing_address_1'])){$validation_errors->add('billing_address_1_error',__('An address 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;
}
//Below code save extra fields when new user register
add_action('woocommerce_created_customer','my_save_extra_register_fields'); 
function my_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_vat'])){
        update_user_meta($customer_id,'billing_vat',sanitize_text_field($_POST['billing_vat']));
    }
    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_address_1'])){
        update_user_meta($customer_id,'billing_address_1',sanitize_text_field($_POST['billing_address_1']));
    }
    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']));
    }
}

이 과정에서 저를 도와주신 모든 분들께 감사드리며, 이전에 질문했던 내용들도 이제 제 프로젝트 전체가 거의 끝나가고 있기 때문에 스택오버플로우 커뮤니티에서 많은 지원을 해주신 분들께 감사드립니다.

woocommerce_form_field()함수는 a를 지원합니다.country제 생각에는 다음과 같이 할 수 있을 것 같습니다.

/**
 * Add new register fields for WooCommerce registration.
 */
function wooc_extra_register_fields() {

    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
    ));

}
add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );

편집 JS 지원 드롭다운을 받으려면 국가 선택 스크립트를 대기열에 올려야 합니다.

WooCommerce Checkout 페이지의 소스 HTML을 보면 JS plugin을 사용하는 것을 볼 수 있습니다.따라서 추가 ID/클래스를 통과한 후 바닥글로 select2 JS function이라고 합니다.

그래서 당신의 전체 코드는

//to add billing_country
function wh_extra_register_fields()
{
    $countries_obj = new WC_Countries();
    $countries = $countries_obj->get_allowed_countries();
    woocommerce_form_field('billing_country', array(
        'type' => 'select',
        'input_class' => array('myClass'), //<--check this line
        'label' => __('Country'),
        'placeholder' => __('Choose your country.'),
        'options' => $countries,
        'required' => true,
        'clear' => true,
        'default' => 'BE' //<--check this line
    ));
}

add_action('woocommerce_register_form_start', 'wh_extra_register_fields');

//to add js code in My Account page footer
function wh_AccountPageJS()
{
    if (is_account_page())
    {
        echo '<script>jQuery(".myClass").select2();</script>';
    }
}

add_action('wp_footer', 'wh_AccountPageJS', 100);

코드는 활성 하위 테마(또는 테마) 파일에 들어갑니다.또는 플러그인 php 파일에서도 마찬가지입니다.
코드를 테스트하고 작동합니다. 버전 3.0

enter image description here

도움이 되길 바랍니다!

템플릿/함수에 추가합니다.

<?php
$field = [
        'type' => 'country',
        'label' => 'Country',
        'required' => 1,
        'class' => ['address-field']
];
woocommerce_form_field( 'billing_country', $field, '' );
$field = [
    'type' => 'state',
    'label' => 'State',
    'required' => 1,
    'class' => ['address-field'],
    'validate' => ['state']
];
woocommerce_form_field( 'billing_state', $field, '' );
?>

페이지에 wocommerce country-select.js를 다음 형식으로 포함합니다.

<?php
    $handle = 'wc-country-select';
    wp_enqueue_script($handle, get_site_url().'/wp-content/plugins/woocommerce/assets/js/frontend/country-select.min.js', array('jquery'), true);
?>

언급URL : https://stackoverflow.com/questions/43373166/woocommerce-country-selection-on-registration