Сохраните значения дополнительных полей из блоков оформления заказа WooCommerce.Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Сохраните значения дополнительных полей из блоков оформления заказа WooCommerce.

Сообщение Anonymous »

Я разрабатываю плагин платежного шлюза для блоков WooCommerce (Гутенберг). Мне нужно создать собственное поле оформления заказа в блоке адреса.
Мне удалось это сделать, но теперь я застрял в том, как передать значения из внешнего интерфейса во внутренний.Последние 3 поля являются настраиваемыми:
Изображение

Код, генерирующий поля, следующий:
(function () {
document.addEventListener('DOMContentLoaded', function() {
// Helper function to create a custom field
function createCustomField(options) {
const { formId, fieldId, labelText, validationMessage, inputName } = options;
const form = document.getElementById(formId);

if (form && !document.getElementById(fieldId)) {
const customFieldWrapper = document.createElement('div');
customFieldWrapper.classList.add('wc-block-components-text-input');
customFieldWrapper.classList.add(`wc-block-components-address-form__${fieldId}`);

const label = document.createElement('label');
label.setAttribute('for', fieldId);
label.textContent = labelText;

const input = document.createElement('input');
input.type = 'text';
input.id = fieldId;
input.name = inputName; // Set the name attribute
input.ariaLabel = labelText;
input.required = true;

input.addEventListener('focus', function () {
customFieldWrapper.classList.add('is-active');
});

input.addEventListener('blur', function () {
const fieldValue = this.value.trim();

if (!fieldValue) {
customFieldWrapper.classList.add('has-error');
customFieldWrapper.classList.remove('is-active');

let warningDiv = document.getElementById(`warning-div-${fieldId}`);
if (warningDiv) {
warningDiv.remove();
}

warningDiv = document.createElement('div');
warningDiv.classList.add("wc-block-components-validation-error");
warningDiv.id = `warning-div-${fieldId}`;

const warningText = document.createElement('p');
warningText.textContent = validationMessage;
warningDiv.appendChild(warningText);

customFieldWrapper.appendChild(warningDiv);
} else {
customFieldWrapper.classList.remove('has-error');
const warningDiv = document.getElementById(`warning-div-${fieldId}`);
if (warningDiv) {
warningDiv.remove();
}
}
});

customFieldWrapper.appendChild(label);
customFieldWrapper.appendChild(input);
form.appendChild(customFieldWrapper);
}
}

const observer = new MutationObserver(function() {
createCustomField({
formId: 'billing',
fieldId: 'billing-neighborhood',
labelText: 'Bairro',
validationMessage: 'Por favor preencha o Bairro',
inputName: 'billing_neighborhood' // Added name attribute
});

createCustomField({
formId: 'billing',
fieldId: 'billing-street-number',
labelText: 'Número',
validationMessage: 'Por favor preencha o Número',
inputName: 'billing_number' // Added name attribute
});

createCustomField({
formId: 'billing',
fieldId: 'billing-cpf',
labelText: 'CPF',
validationMessage: 'Por favor preencha o CPF',
inputName: 'billing_cpf' // Added name attribute
});
});

observer.observe(document.body, { childList: true, subtree: true });
});

})();

Я пытаюсь получить поля в моем основном файле плагина (имя-плагина.php) таким способом, но ничего не получается...
//WooCommerce Blocks
add_action('woocommerce_store_api_checkout_update_order_meta', 'save_custom_checkout_fields', 10, 2);
function save_custom_checkout_fields($order) {
$logger = wc_get_logger();
$logger-\>info('Entered on woocommerce_store_api_checkout_update_order_meta', array( 'source' =\> 'aditum-pix-meta' ));
$logger-\>info(wc_print_r( $order, true ), array( 'source' =\> 'aditum-pix-meta' ));

if (isset($_POST['billing_neighborhood'])) {
$neighborhood = sanitize_text_field($_POST['billing_neighborhood']);
$order->update_meta_data('_billing_neighborhood', $neighborhood);
$logger->info('Billing Neighborhood: ' . $neighborhood, array( 'source' => 'aditum-pix-meta' ));
}

if (isset($_POST['billing_street_number'])) {
$street_number = sanitize_text_field($_POST['billing_street_number']);
$order->update_meta_data('_billing_street_number', $street_number);
$logger->info('Billing Street Number: ' . $street_number, array( 'source' => 'aditum-pix-meta' ));
}

if (isset($_POST['billing_cpf'])) {
$cpf = sanitize_text_field($_POST['billing_cpf']);
$order->update_meta_data('_billing_cpf', $cpf);
$logger->info('Billing CPF: ' . $cpf, array( 'source' => 'aditum-pix-meta' ));
}

}

Когда журнал печатает $order, это то, чем заполняется объект биллинга:
[billing] => Array
(
[first_name] => asd
[last_name] => asdasd
[company] =>
[address_1] => asd
[address_2] => 123
[city] => asd
[state] => SP
[postcode] => 03530-110
[country] => BR
[email] => asd@asd.com
[phone] =>
)


Подробнее здесь: https://stackoverflow.com/questions/790 ... out-blocks
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»