Я использую код PHP и JavaScript на своем веб-сайте WooCommerce для отображения встроенных сообщений об ошибках на странице оформления заказа wooocommerce.
В настоящее время сообщение об ошибке появляется несколько раз, когда любое обязательное поле пусто. из-за петли в коде. Когда я выношу код обработки ошибок за пределы цикла, сообщение отображается только один раз, но затем система не перенаправляет меня на страницу оплаты. Я хотел бы отобразить сообщение проверки ошибки «Упс, похоже, некоторая информация отсутствует. Пожалуйста, заполните все *обязательные поля, чтобы мы могли выполнить ваш заказ» только один раз, чтобы гарантировать, что меня все равно можно будет перенаправить на страницу оплаты.< /p>
PHP-код:
add_action( 'woocommerce_after_checkout_form', 'add_custom_validation_script', 20 );
function add_custom_validation_script() {
wp_enqueue_script(
'inline_validation_script',
get_stylesheet_directory_uri() . '/js/inline-validation.js',
['jquery']
);
}
/**
* adds error message field element to get inline error messages working
*
* @param array $fields
* @param object $errors
*/
add_filter( 'woocommerce_form_field', 'add_inline_error_messages_element', 10, 4 );
function add_inline_error_messages_element( $field, $key, $args, $value ) {
if ( strpos( $field, '' ) !== false ) {
$error = '';
$field = substr_replace( $field, $error, strpos( $field, '' ), 0);
}
return $field;
}
/**
* process custom checkout validations
*
* @param array $fields
* @param object $errors
*/
add_action('woocommerce_after_checkout_validation', 'custom_checkout_validations', 10, 2);
function custom_checkout_validations($data, $errors){
$your_custom_checkout_field = filter_input(INPUT_POST, 'your_custom_input_field');
// your custom validations goes here
// this loop adds a data array to all error messages which will be applied as a "data-error-for" HTML attribute
// to read out the corresponding field ids with javascript and display the error messages inline
foreach( $errors->errors as $original_key => $error ) {
$field_key = $original_key;
// filter and rewrite the field id for native woocommerce error messages with a key containing _required
if(strpos($original_key, '_required') !== false) {
$field_key = str_replace('_required','', $original_key);
$error[0] = __('This is a required field', 'YourThemeName');
if( !empty($errors->get_error_codes() ) ) {
$errors->add( 'validation', 'O o o p s, looks like some info is missing. Please fill in all *Required fields so we can complete your order.' );
}
}
// switch out the old error messages with the ones including a spiced up data array
// to display with javascript
$errors->remove($original_key);
$errors->add($original_key, trim($error[0]), ['error-for' => $field_key . '_field']);
}
}
JS-код:
jQuery(function ($) {
'use strict';
addInlineMessages();
// Implementation
// Listen to js event
$(document.body).on('updated_checkout', function() {
addInlineMessages();
});
function addInlineMessages() {
var woocommerceErrorsEl = $('.woocommerce-error');
var woocommerceInlineErrorsEl = $('li[data-error-for]', woocommerceErrorsEl);
var inlineErrorMessagesEl = $('.js-custom-error-message');
// as we use ajax submitting hide old validation messages
if(inlineErrorMessagesEl.length) {
inlineErrorMessagesEl.hide();
}
if(woocommerceInlineErrorsEl.length) {
woocommerceInlineErrorsEl.each(function () {
var errorEl = $(this);
var errorText = $.trim(errorEl.text());
var targetFieldId = errorEl.data('error-for');
if(errorText && targetFieldId) {
var targetFieldEl = $('#' + targetFieldId);
var errorMessageField = $('.js-custom-error-message', targetFieldEl);
if(targetFieldEl.length && errorMessageField.length) {
targetFieldEl.addClass('woocommerce-invalid');
errorMessageField.text(errorText);
errorMessageField.show();
errorEl.hide();
}
}
});
if(woocommerceInlineErrorsEl.filter(':visible').length === 0) {
if(inlineErrorMessagesEl.filter(':visible').length > 0) {
scrollToElement(inlineErrorMessagesEl.filter(':visible').first());
}
} else {
$('li:not([data-error-for])', woocommerceErrorsEl).hide();;
scrollToElement(woocommerceErrorsEl);
}
}
}
function scrollToElement(el) {
if(el.length) {
$([document.documentElement, document.body]).animate({
scrollTop: el.offset().top - 100
}, 2000);
}
}
// event listeners
$(document.body).on('checkout_error', function (event) {
jQuery('html, body').stop();
addInlineMessages();
});
});
Подробнее здесь: https://stackoverflow.com/questions/791 ... y-one-time
Как я могу показать сообщение об ошибке только один раз? ⇐ Php
Кемеровские программисты php общаются здесь
-
Anonymous
1730887534
Anonymous
Я использую код PHP и JavaScript на своем веб-сайте WooCommerce для отображения встроенных сообщений об ошибках на странице оформления заказа wooocommerce.
В настоящее время сообщение об ошибке появляется несколько раз, когда любое обязательное поле пусто. из-за петли в коде. Когда я выношу код обработки ошибок за пределы цикла, сообщение отображается только один раз, но затем система не перенаправляет меня на страницу оплаты. Я хотел бы отобразить сообщение проверки ошибки «Упс, похоже, некоторая информация отсутствует. Пожалуйста, заполните все *обязательные поля, чтобы мы могли выполнить ваш заказ» только один раз, чтобы гарантировать, что меня все равно можно будет перенаправить на страницу оплаты.< /p>
PHP-код:
add_action( 'woocommerce_after_checkout_form', 'add_custom_validation_script', 20 );
function add_custom_validation_script() {
wp_enqueue_script(
'inline_validation_script',
get_stylesheet_directory_uri() . '/js/inline-validation.js',
['jquery']
);
}
/**
* adds error message field element to get inline error messages working
*
* @param array $fields
* @param object $errors
*/
add_filter( 'woocommerce_form_field', 'add_inline_error_messages_element', 10, 4 );
function add_inline_error_messages_element( $field, $key, $args, $value ) {
if ( strpos( $field, '' ) !== false ) {
$error = '';
$field = substr_replace( $field, $error, strpos( $field, '' ), 0);
}
return $field;
}
/**
* process custom checkout validations
*
* @param array $fields
* @param object $errors
*/
add_action('woocommerce_after_checkout_validation', 'custom_checkout_validations', 10, 2);
function custom_checkout_validations($data, $errors){
$your_custom_checkout_field = filter_input(INPUT_POST, 'your_custom_input_field');
// your custom validations goes here
// this loop adds a data array to all error messages which will be applied as a "data-error-for" HTML attribute
// to read out the corresponding field ids with javascript and display the error messages inline
foreach( $errors->errors as $original_key => $error ) {
$field_key = $original_key;
// filter and rewrite the field id for native woocommerce error messages with a key containing _required
if(strpos($original_key, '_required') !== false) {
$field_key = str_replace('_required','', $original_key);
$error[0] = __('This is a required field', 'YourThemeName');
if( !empty($errors->get_error_codes() ) ) {
$errors->add( 'validation', 'O o o p s, looks like some info is missing. Please fill in all *Required fields so we can complete your order.' );
}
}
// switch out the old error messages with the ones including a spiced up data array
// to display with javascript
$errors->remove($original_key);
$errors->add($original_key, trim($error[0]), ['error-for' => $field_key . '_field']);
}
}
JS-код:
jQuery(function ($) {
'use strict';
addInlineMessages();
// Implementation
// Listen to js event
$(document.body).on('updated_checkout', function() {
addInlineMessages();
});
function addInlineMessages() {
var woocommerceErrorsEl = $('.woocommerce-error');
var woocommerceInlineErrorsEl = $('li[data-error-for]', woocommerceErrorsEl);
var inlineErrorMessagesEl = $('.js-custom-error-message');
// as we use ajax submitting hide old validation messages
if(inlineErrorMessagesEl.length) {
inlineErrorMessagesEl.hide();
}
if(woocommerceInlineErrorsEl.length) {
woocommerceInlineErrorsEl.each(function () {
var errorEl = $(this);
var errorText = $.trim(errorEl.text());
var targetFieldId = errorEl.data('error-for');
if(errorText && targetFieldId) {
var targetFieldEl = $('#' + targetFieldId);
var errorMessageField = $('.js-custom-error-message', targetFieldEl);
if(targetFieldEl.length && errorMessageField.length) {
targetFieldEl.addClass('woocommerce-invalid');
errorMessageField.text(errorText);
errorMessageField.show();
errorEl.hide();
}
}
});
if(woocommerceInlineErrorsEl.filter(':visible').length === 0) {
if(inlineErrorMessagesEl.filter(':visible').length > 0) {
scrollToElement(inlineErrorMessagesEl.filter(':visible').first());
}
} else {
$('li:not([data-error-for])', woocommerceErrorsEl).hide();;
scrollToElement(woocommerceErrorsEl);
}
}
}
function scrollToElement(el) {
if(el.length) {
$([document.documentElement, document.body]).animate({
scrollTop: el.offset().top - 100
}, 2000);
}
}
// event listeners
$(document.body).on('checkout_error', function (event) {
jQuery('html, body').stop();
addInlineMessages();
});
});
Подробнее здесь: [url]https://stackoverflow.com/questions/79162110/how-can-i-show-the-error-message-only-one-time[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия