2016-08-24 1 views
3

Я использую этот код для создания пользовательских полей проверочные и изменить порядок полей:Пользовательские выпадающий селектор отображения или скрытия других Checkout пользовательских полей

add_filter('woocommerce_checkout_fields', 'custom_checkout_billing_fields'); 
function custom_checkout_billing_fields($fields) { 

// 1. Creating the additional custom billing fields 

    // The "status" selector 
    $fields['billing']['billing_status']['type'] = 'select'; 
    $fields['billing']['billing_status']['class'] = array('form-row-wide, status-select'); 
    $fields['billing']['billing_status']['required'] = true; 
    $fields['billing']['billing_status']['label'] = __('User status', 'my_theme_slug'); 
    $fields['billing']['billing_status']['placeholder'] = __('Chose an option', 'my_theme_slug'); 
    $fields['billing']['billing_status']['options'] = array(
     '' => 'Chose an option', 
     '1' => 'Legal entity', 
     '2' => 'Individual' 
    ); 

    // The "Serial ID" text field 
    $fields['billing']['billing_number_id']['type'] = 'text'; 
    $fields['billing']['billing_number_id']['class'] = array('form-row-wide', 'status-group1'); 
    $fields['billing']['billing_number_id']['required'] = true; 
    $fields['billing']['billing_number_id']['label'] = __('Serial ID', 'my_theme_slug'); 
    $fields['billing']['billing_number_id']['placeholder'] = __('Enter your Serial ID', 'my_theme_slug'); 

    // Customizing 'billing_company' field ['required'] 
    $fields['billing']['billing_company']['required'] = false; 

    // The "Serial ID" text field 
    $fields['billing']['billing_serial']['type'] = 'text'; 
    $fields['billing']['billing_serial']['class'] = array('form-row-wide', 'status-group1'); 
    $fields['billing']['billing_serial']['required'] = false; 
    $fields['billing']['billing_serial']['label'] = __('Serial ID', 'my_theme_slug'); 
    $fields['billing']['billing_serial']['placeholder'] = __('Enter your Serial ID', 'my_theme_slug'); 


// 2. Customizing 'billing_email' and 'billing_phone' fields ['class'] 

    $fields['billing']['billing_email']['class'] = array('form-row-first', 'status-group1'); 
    $fields['billing']['billing_phone']['class'] = array('form-row-last', 'status-group1'); 


// 3. Ordering the billing fields 

    $fields_order = array(
     'billing_first_name', 'billing_last_name', 'billing_email', 
     'billing_phone',  'billing_address_1', 'billing_address_2', 
     'billing_postcode', 'billing_city',  'billing_country', 
     'billing_status', 
     'billing_company', 'billing_number_id', 'billing_serial' 
    ); 
    foreach($fields_order as $field) $ordered_fields[$field] = $fields['billing'][$field]; 

    $fields['billing'] = $ordered_fields; 


// Returning Checkout customized billing fields 

    return $fields; 

} 

Условный механизм:

  1. По умолчанию billing_status выпадающий селектор будет на Individual значение опции и покажет только billing_serial пользовательское поле.
  2. Когда селектор billing_status выпадающих будет переключен на "Company" ** значение параметра, появится еще 2 поля:
    • billing_company существующего поля (до billing_serial)
    • billing_number_id пользовательских полей (на конец)

Как я могу это достичь?

Благодаря


Ссылка: WooCommerce - Checkout conditional fields for different persons custom status

+0

Это просто, пользователь завершит только имя, и фамилия, после этого он выберет статус своего лица, если он является юридическим лицом или физическим лицом. Если он выберет из раскрывающегося меню выбора индивидуальный статус, поле, которое должно отображаться, будет являться телефоном, адресом, электронной почтой и серийным идентификатором. Если он является юридическим лицом, мне нужно следующие поля: - телефон - электронный - адрес - порядковый номер документа для компании - и 3 других областей –

+0

нормально, причина того, что я хочу, эта структура является то, что если я хочу вывести счет-фактуру на эти данные в зависимости от типа человека. Теперь есть смысл? –

+0

Привлечение данных к благодарности и счету будет будущим другим вопросам, я думаю :) – LoicTheAztec

ответ

2

Для WooCommerce 3+ (обновление):

С WooCommerce 3.0 Кассовые полей изменились немного, так невозможно изменить порядок полей как befo число рейнольдса

Существует новый «приоритет» аргумент , которые обрабатывают поля заказа, для кассовых полей и моих полей учетной записи, а также.

Ниже я просто обновляя часть связанных с упорядочением полей:

## 3. Ordering the billing fields 

// Set the order of the fields 
$billing_fields_new_order = array(
    'billing_first_name', 'billing_last_name', 'billing_email', 
    'billing_phone',  'billing_address_1', 'billing_address_2', 
    'billing_postcode', 'billing_city',  'billing_country', 
    'billing_status', 
    'billing_company', 'billing_number_id', 'billing_ser_id' 
); 

$count = 0; 
$priority = 10; 

// Updating the 'priority' argument 
foreach($billing_fields_new_order as $field_name){ 
    $count++; 
    $fields['billing'][$field_name]['priority'] = $count * $priority; 
} 

// END: returning the customized checkout fields 
return $fields; 

Ссылка:Reordering checkout fields in WooCommerce 3


Оригинальный ответ:

Вот решение с jQu ery/JS, чтобы заставить работать условный механизм так же, как вы ожидаете ... PHP-код комплектуется некоторыми необходимыми функциями ...

Код PHP (входит в функцию.PHP):

// Registering external jQuery/JS file 
function cfields_scripts() { 

    /* IMPORTANT NOTE: For a child theme replace get_template_directory_uri() by get_stylesheet_directory_uri() 
         The external cfields.js file goes in a subfolder "js" of your active child theme or theme.*/ 

    wp_enqueue_script('checkout_script', get_template_directory_uri().'/js/cfields.js', array('jquery'), '1.0', true); 
} 
add_action('wp_enqueue_scripts', 'cfields_scripts'); 


add_filter('woocommerce_checkout_fields', 'custom_checkout_billing_fields'); 
function custom_checkout_billing_fields($fields) { 

// 1. Creating the additional custom billing fields 

    // The "status" selector 
    $fields['billing']['billing_status']['type'] = 'select'; 
    $fields['billing']['billing_status']['class'] = array('form-row-wide, status-select'); 
    $fields['billing']['billing_status']['required'] = true; 
    $fields['billing']['billing_status']['label'] = __('User status', 'my_theme_slug'); 
    $fields['billing']['billing_status']['placeholder'] = __('Chose an option', 'my_theme_slug'); 
    $fields['billing']['billing_status']['options'] = array(
     '1' => __('Individual', ''), 
     '2' => __('Company', '') 
    ); 

    // Customizing 'billing_company' field ['required'] 
    $fields['billing']['billing_company']['required'] = false; 
    $fields['billing']['billing_company']['class'] = array('form-row-wide', 'status-group2'); 

    // The "Number ID" text field 
    $fields['billing']['billing_number_id']['type'] = 'text'; 
    $fields['billing']['billing_number_id']['class'] = array('form-row-wide'); 
    $fields['billing']['billing_number_id']['required'] = true; 
    $fields['billing']['billing_number_id']['label'] = __('Number ID', 'my_theme_slug'); 
    $fields['billing']['billing_number_id']['placeholder'] = __('Enter your Number ID', 'my_theme_slug'); 

    // The "Serial identification" text field 
    $fields['billing']['billing_ser_id']['type'] = 'text'; 
    $fields['billing']['billing_ser_id']['class'] = array('form-row-wide', 'status-group2'); 
    $fields['billing']['billing_ser_id']['required'] = false; 
    $fields['billing']['billing_ser_id']['label'] = __('Serial identification', 'my_theme_slug'); 
    $fields['billing']['billing_ser_id']['placeholder'] = __('Enter your Serial identification', 'my_theme_slug'); 


// 3. Ordering the billing fields 

    $fields_order = array(
     'billing_first_name', 'billing_last_name', 'billing_email', 
     'billing_phone',  'billing_address_1', 'billing_address_2', 
     'billing_postcode', 'billing_city',  'billing_country', 
     'billing_status', 
     'billing_company', 'billing_number_id', 'billing_ser_id' 
    ); 
    foreach($fields_order as $field) $ordered_fields[$field] = $fields['billing'][$field]; 

    $fields['billing'] = $ordered_fields; 


// Returning Checkout customized billing fields 

    return $fields; 

} 


// Process the checkout 
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process'); 
function custom_checkout_field_process() { 
    // Check if set, if its not set add an error. 
    if (! $_POST['billing_number_id']) 
     wc_add_notice(__('Please enter your Number ID.', 'my_theme_slug'), 'error'); 
    if (! $_POST['billing_ser_id']) 
     wc_add_notice(__('Please enter your Serial id.' , 'my_theme_slug'), 'error'); 
} 

// Update the order meta with field value 
add_action('woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta'); 
function custom_checkout_field_update_order_meta($order_id) { 
    if (! empty($_POST['billing_number_id'])) 
     update_post_meta($order_id, 'billing_number_id', sanitize_text_field($_POST['billing_number_id'])); 
    if (! empty($_POST['billing_ser_id'])) 
     update_post_meta($order_id, 'billing_ser_id', sanitize_text_field($_POST['billing_ser_id'])); 
} 


// Display field value on the order edit page 
add_action('woocommerce_admin_order_data_after_billing_address', 'custom_checkout_field_display_admin_order_meta', 10, 1); 
function custom_checkout_field_display_admin_order_meta($order){ 
    echo '<p><strong>'.__('My number ID').':</strong> ' . get_post_meta($order->id, 'billing_number_id', true) . '</p>'; 
    echo '<p><strong>'.__('My serial identification').':</strong> ' . get_post_meta($order->id, 'billing_ser_id', true) . '</p>'; 
} 

Javascript cfields.js код (внешний файл):

// This file named "cfields.js" goes in a subfolder "js" of your active child theme or theme 

jQuery(document).ready(function($){ 

    $('#billing_company_field').hide(function(){ 
     $(this).removeClass("validate-required"); 
    }); 
    $('#billing_ser_id_field').hide(function(){ 
     $(this).removeClass("validate-required"); 
    }); 
    $("#billing_number_id_field").addClass("validate-required"); 

    $("#billing_status").change(function(){ 
     if($("#billing_status option:selected").val() == "2"){ 
      $('#billing_company_field').show(function(){ 
       $(this).addClass("validate-required"); 
      }); 
      $('#billing_ser_id_field').show(function(){ 
       $(this).addClass("validate-required"); 
      }); 
     } else if($("#billing_status option:selected").val() == "1"){ 
      $('#billing_company_field').hide(function(){ 
       $(this).removeClass("validate-required"); 
      }); 
      $('#billing_ser_id_field').hide(function(){ 
       $(this).removeClass("validate-required"); 
      }); 
     } 

    }); 

}); 

Весь этот код был проверен и работает

+0

Здравствуйте Loic, у меня есть небольшая проблема, я хочу добавить еще 3 поля для юридического лица: название банка, банковский счет и регистрационный номер .. я не могу этого сделать, вы можете мне помочь, спасибо заранее. @loictheaztec –

Смежные вопросы