Как отметил @Peanuts, что, если мы хотим добавить классы CSS только к определенным типам ввода?
Поэкспериментировав с решениями, опубликованными здесь (спасибо всем!), Я придумал мод, использующий простой «случай переключения», в котором логика взята из /woocommerce/includes/wc-template-functions.php
. Функция позволяет нам настроить таргетинг на все типы ввода одновременно, будь то типы ввода по умолчанию или даже пользовательские.
Нет необходимости переписывать woocommerce_form_field
функцию, чтобы просто изменить $defaults
аргументы для типов ввода. Следует отметить, что эта функция также позволяет нам добавлять в поля гораздо больше, чем просто классы CSS.
- Итак, вот функция -
/*********************************************************************************************/
/** WooCommerce - Modify each individual input type $args defaults /**
/*********************************************************************************************/
add_filter('woocommerce_form_field_args','wc_form_field_args',10,3);
function wc_form_field_args( $args, $key, $value = null ) {
/*********************************************************************************************/
/** This is not meant to be here, but it serves as a reference
/** of what is possible to be changed. /**
$defaults = array(
'type' => 'text',
'label' => '',
'description' => '',
'placeholder' => '',
'maxlength' => false,
'required' => false,
'id' => $key,
'class' => array(),
'label_class' => array(),
'input_class' => array(),
'return' => false,
'options' => array(),
'custom_attributes' => array(),
'validate' => array(),
'default' => '',
);
/*********************************************************************************************/
// Start field type switch case
switch ( $args['type'] ) {
case "select" : /* Targets all select input type elements, except the country and state select input types */
$args['class'][] = 'form-group'; // Add a class to the field's html element wrapper - woocommerce input types (fields) are often wrapped within a <p></p> tag
$args['input_class'] = array('form-control', 'input-lg'); // Add a class to the form input itself
//$args['custom_attributes']['data-plugin'] = 'select2';
$args['label_class'] = array('control-label');
$args['custom_attributes'] = array( 'data-plugin' => 'select2', 'data-allow-clear' => 'true', 'aria-hidden' => 'true', ); // Add custom data attributes to the form input itself
break;
case 'country' : /* By default WooCommerce will populate a select with the country names - $args defined for this specific input type targets only the country select element */
$args['class'][] = 'form-group single-country';
$args['label_class'] = array('control-label');
break;
case "state" : /* By default WooCommerce will populate a select with state names - $args defined for this specific input type targets only the country select element */
$args['class'][] = 'form-group'; // Add class to the field's html element wrapper
$args['input_class'] = array('form-control', 'input-lg'); // add class to the form input itself
//$args['custom_attributes']['data-plugin'] = 'select2';
$args['label_class'] = array('control-label');
$args['custom_attributes'] = array( 'data-plugin' => 'select2', 'data-allow-clear' => 'true', 'aria-hidden' => 'true', );
break;
case "password" :
case "text" :
case "email" :
case "tel" :
case "number" :
$args['class'][] = 'form-group';
//$args['input_class'][] = 'form-control input-lg'; // will return an array of classes, the same as bellow
$args['input_class'] = array('form-control', 'input-lg');
$args['label_class'] = array('control-label');
break;
case 'textarea' :
$args['input_class'] = array('form-control', 'input-lg');
$args['label_class'] = array('control-label');
break;
case 'checkbox' :
break;
case 'radio' :
break;
default :
$args['class'][] = 'form-group';
$args['input_class'] = array('form-control', 'input-lg');
$args['label_class'] = array('control-label');
break;
}
return $args;
}
Вышеупомянутая функция полностью решила проблему одновременного нацеливания всех входных данных формы оформления заказа, что действительно очевидно для типов ввода по умолчанию для формы оформления заказа или даже для новых пользовательских типов. Однако, похоже, невозможно распечатать каждый вывод html типа ввода без создания новой функции, как @abhisek показывает в своем ответе.
Бонус
Кажется, что эта функция также может влиять на другие поля форм, напечатанные функциями или шаблонами WooCommerce за пределами страницы оформления заказа. Мне удалось условно применить функцию только на странице оформления заказа с помощью функции is_page()
. На вашей странице оформления заказа может быть другой ярлык, поэтому измените его, чтобы он отражался соответствующим образом.
Если вам нужно применить функцию только для страницы оформления заказа, сделайте следующее:
Комментарий add_filter ()
//add_filter('woocommerce_form_field_args','wc_form_field_args', 10, 3);
И вместо этого используйте add_action
add_action('woocommerce_form_field_args', 'wc_form_field_args', 10, 3);
function wc_form_field_args( $args, $key, $value = null ) {
...
// Right after
return $args;
// Place the following
if ( !is_page('checkout') ) {
add_filter('woocommerce_form_field_args','wc_form_field_args', 10, 3);
} else {
remove_filter('woocommerce_form_field_args','wc_form_field_args', 10, 3);
}
}
После этого функция повлияет только на форму страницы оформления заказа.
person
Adriano Monecchi
schedule
19.04.2016