Я хочу создать поле проверки WooCommerce, которое отображается только при выборе определенного платежа (наложенным платежом). Это поле должно отображаться и быть обязательным только при выборе наложенного платежа. Мне удалось сделать поле и показать его условно, но я не могу понять, как сделать его обязательным только при выборе COD.
/* Only show EAN when COD chosen */
// Conditional Show hide checkout fields based on chosen payment methods
add_action( 'wp_footer', 'conditionally_show_hide_billing_custom_field' );
function conditionally_show_hide_billing_custom_field(){
// Only on checkout page
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script>
jQuery(function($){
var a = 'input[name = "payment_method"]',
b = a + ':checked',
c = '#billing_options_field'; // The checkout field <p> container selector
// Function that shows or hide checkout fields
function showHide( selector = '', action = 'show' ){
if ( action == 'show' )
$(selector).show( 200, function(){
$(this).addClass("validate-required");
});
else
$(selector).hide( 200, function(){
$(this).removeClass("validate-required");
});
$(selector).removeClass("woocommerce-validated");
$(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
}
// Initialising: Hide if choosen payment method is "cod"
if ( $(b).val() !== 'cod' )
showHide( c, 'hide' );
else
showHide( c );
// Live event (When payment method is changed): Show or Hide based on "cod"
$( 'form.checkout' ).on( 'change', a, function() {
if ( $(b).val() !== 'cod' )
showHide( c, 'hide' );
else
showHide( c );
});
});
</script>
<?php
endif;
}
/* Add extra field and make it required */
add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');
function custom_woocommerce_billing_fields($fields)
{
$fields['billing_options'] = array(
'label' => __('– EAN-nummer – ', 'woocommerce'), // Add custom field label
'placeholder' => _x('EAN nummer', 'placeholder', 'woocommerce'), // Add custom field placeholder
'required' => true, // if field is required or not
'clear' => false, // add clear or not
'type' => 'text', // add field type
'class' => array('my-css') // add class name
);
return $fields;
}
add_action('woocommerce_after_checkout_validation', 'woocommerce_after_checkout_validation_alter', 10, 2);
function woocommerce_after_checkout_validation_alter($data, $errors){
if ('cod' !== $data['payment_method']){
if ($errors->get_error_data('billing_options_required')){ // This will contain the error
$errors->remove('billing_options_required');
}
}
return $data;
}
Удалите ошибку проверки из объекта ошибки, если выбранный способ оплаты не наложенным платежом. Объект ошибки будет таким, как показано ниже.
WP_Error Object
(
[errors] => Array
(
[billing_options_required] => Array
(
[0] => <strong>Billing – EAN-nummer – </strong> is a required field.
)
)
[error_data] => Array
(
[billing_options_required] => Array
(
[id] => billing_options
)
)
[additional_data:protected] => Array
(
)
)
Добавьте фрагмент кода, который я добавил, вместе с вашим фрагментом кода. Вот и все.
Ааа - это имеет смысл, спасибо. Извини за это. Когда я добавляю код поверх моего, я получаю следующую ошибку в объекте WP_Errors: Синтаксическая ошибка, непредвиденная строка T
О, нет. Вам просто нужно скопировать и вставить только фрагмент кода. Не раздел WP_Error
Не рекомендуется анализировать ошибку woocomerce после проверки, гораздо лучше сначала правильно обработать проверку.
Чтобы условно установить поле в соответствии с требованиями при оформлении заказа, гораздо лучше использовать хук woocommerce_checkout_fields, чтобы мы могли вносить любые изменения до обработки формы, эта функция позволяет программно получить доступ и установить значения каждого поля оформления заказа, а также может быть скопированным/вставленным в ваш файл functions.php для достижения того, что вы ищете.
/**
* Skip Validation for EAN field when COD is not chosen
*
* @param array $fields
* @return array
*/
function woocommerce_no_ean( array $fields ): array {
// bail if the payment method is not COD
if ( ! isset( $_POST['payment_method'] ) || 'cod' === $_POST['payment_method'] ) {
return $fields;
}
$fields['billing']['billing_options']['required'] = false;
return $fields;
} add_filter( 'woocommerce_checkout_fields', 'woocommerce_no_ean' );
Кроме того, вот еще несколько советов:
Всегда полезно проверить любые данные формы, особенно данные проверки, чтобы убедиться, что они действительны, после быстрого поиска в Google, если по номеру EAN вы имеете в виду Это Я сделал дополнительную функцию для вас, чтобы проверить, что поле 13 чисел, если вы хотите использовать их, просто поместите их в свой файл функций.
/**
* Validate the EAN field on checkout submission
*
* This is a simple example of how to validate a custom field on checkout submission,
* for the EAN field we are checking if the value is numeric and if it's 13 digits long.
*
* To remove the validation, simply remove the add_action() function and everything after it.
*
* @return void
* @see https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
*/
function woocomerce_validate_ean(): void {
// validate the woocommerce nonce
if ( ! isset( $_POST['woocommerce-process-checkout-nonce'] ) || ! wp_verify_nonce( $_POST['woocommerce-process-checkout-nonce'], 'woocommerce-process_checkout' ) ) {
wc_add_notice( __( 'Checkout Validation Error, Please Try Refreshing The Page' ), 'error' );
return;
}
// bail if the payment method is not COD
if ( ! isset( $_POST['payment_method'] ) || 'cod' !== $_POST['payment_method'] ) {
return;
}
if ( ! isset( $_POST['billing_options'] ) || empty( $_POST['billing_options'] ) ||
! is_numeric( $_POST['billing_options'] )
|| ! preg_match( '/^[0-9]{13}$/', $_POST['billing_options'] ) ) {
wc_add_notice( ( 'Please enter a valid EAN number.' ), 'error' );
wc_add_notice( ( 'EAN number must be 13 digits.' ), 'notice' );
}
} add_action( 'woocommerce_checkout_process', 'woocomerce_validate_ean' );
Также рекомендуется не помещать слишком много javascript в ваши php-файлы, поэтому я бы рекомендовал использовать хук wp_enqueue_scripts для условной загрузки ваших javascript-файлов по мере необходимости.
Вы можете заменить весь блок wp-footer этим
/**
* enqueue custom ean javascript
*
* This is assuming that you have a file located at {theme_root}/assets/js/eancheckout.js
*/
function enqueue_ean_checkout_js() {
if ( is_checkout() ) {
wp_enqueue_script( 'ean-checkout-js', get_stylesheet_directory_uri() . '/assets/js/eancheckout.js', array( 'jquery' ), '1.0', true );
}
} add_action( 'wp_enqueue_scripts', 'enqueue_ean_checkout_js' );
И создайте файл с именем eancheckout.js в вашей папке theme/assets/js, например
// Conditional Show hide checkout fields based on chosen payment methods
(($) => {
'use strict';
var a = 'input[name = "payment_method"]',
b = a + ':checked',
c = '#billing_options_field'; // The checkout field <p> container selector
// Function that shows or hide checkout fields
function showHide(selector = '', action = 'show') {
if (action == 'show')
$(selector).show(200, function() {
$(this).addClass("validate-required");
});
else
$(selector).hide(200, function() {
$(this).removeClass("validate-required");
});
$(selector).removeClass("woocommerce-validated");
$(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
}
// Initialising: Hide if choosen payment method is "cod"
if ($(b).val() !== 'cod')
showHide(c, 'hide');
else
showHide(c);
// Live event (When payment method is changed): Show or Hide based on "cod"
$('form.checkout').on('change', a, function() {
if ($(b).val() !== 'cod')
showHide(c, 'hide');
else
showHide(c);
});
})(jQuery);
Итак, если вы хотите реализовать все это, просто создайте этот файл js, и это полный результат файла functions.php для этого.
/**
* enqueue custom ean javascript
*
* This is assuming that you have a file located at {theme_root}/assets/js/eancheckout.js
*/
function enqueue_ean_checkout_js() {
if ( is_checkout() ) {
wp_enqueue_script( 'ean-checkout-js', get_stylesheet_directory_uri() . '/assets/js/eancheckout.js', array( 'jquery' ), '1.0', true );
}
} add_action( 'wp_enqueue_scripts', 'enqueue_ean_checkout_js' );
/* Add extra field and make it required */
function custom_woocommerce_billing_fields( $fields ) {
$fields['billing_options'] = array(
'label' => __( 'EAN-nummer', 'woocommerce' ), // Add custom field label
'placeholder' => _x( 'EAN nummer', 'placeholder', 'woocommerce' ), // Add custom field placeholder
'required' => true, // if field is required or not
'clear' => false, // add clear or not
'type' => 'text', // add field type
'class' => array( 'my-css' ), // add class name
);
return $fields;
} add_filter( 'woocommerce_billing_fields', 'custom_woocommerce_billing_fields' );
/**
* Skip Validation for EAN field when COD is not chosen
*
* @param array $fields
* @return array
*/
function woocommerce_no_ean( array $fields ): array {
// bail if the payment method is not COD
if ( ! isset( $_POST['payment_method'] ) || 'cod' === $_POST['payment_method'] ) {
return $fields;
}
$fields['billing']['billing_options']['required'] = false;
return $fields;
} add_filter( 'woocommerce_checkout_fields', 'woocommerce_no_ean' );
/**
* Validate the EAN field on checkout submission
*
* This is a simple example of how to validate a custom field on checkout submission,
* for the EAN field we are checking if the value is numeric and if it's 13 digits long.
*
* To remove the validation, simply remove the add_action() function and everything after it.
*
* @return void
* @see https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
*/
function woocomerce_validate_ean(): void {
// validate the woocommerce nonce
if ( ! isset( $_POST['woocommerce-process-checkout-nonce'] ) || ! wp_verify_nonce( $_POST['woocommerce-process-checkout-nonce'], 'woocommerce-process_checkout' ) ) {
wc_add_notice( __( 'Checkout Validation Error, Please Try Refreshing The Page' ), 'error' );
return;
}
// bail if the payment method is not COD
if ( ! isset( $_POST['payment_method'] ) || 'cod' !== $_POST['payment_method'] ) {
return;
}
if ( ! isset( $_POST['billing_options'] ) || empty( $_POST['billing_options'] ) ||
! is_numeric( $_POST['billing_options'] )
|| ! preg_match( '/^[0-9]{13}$/', $_POST['billing_options'] ) ) {
wc_add_notice( ( 'Please enter a valid EAN number.' ), 'error' );
wc_add_notice( ( 'EAN number must be 13 digits.' ), 'notice' );
}
} add_action( 'woocommerce_checkout_process', 'woocomerce_validate_ean' );
Здравствуйте, Муджуонли. Спасибо за ответ. Как тогда будет выглядеть общий PHP для добавления к функциям php? Извините, я все еще пытаюсь выучить все это.