Измените стоимость доставки WooCommerce в зависимости от выбранного способа оплаты.Php

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

Сообщение Anonymous »

На странице оформления заказа WooCommerce стоимость доставки не обновляется при изменении типа оплаты, но стоимость доставки меняется при обновлении полей адреса.
Требование:
Если тип оплаты — наложенный платеж, то стоимость доставки — 100;
Если тип оплаты — UPI, то стоимость доставки — 70;
Ниже приведены два файла, которые мы используем для удовлетворить требование
custom-functions.php

Код: Выделить всё

// Adjust shipping cost based on the selected payment method
add_filter('woocommerce_package_rates', 'adjust_shipping_based_on_payment_method', 10, 2);

function adjust_shipping_based_on_payment_method($rates, $package) {
$chosen_payment_method = WC()->session->get('chosen_payment_method');

if ($chosen_payment_method) {
foreach ($rates as $rate_key => $rate) {

if ($chosen_payment_method === 'cod') {

$rates[$rate_key]->cost = 100;
} elseif ($chosen_payment_method === 'wc-upi') {

$rates[$rate_key]->cost = 70;
}
}
}

return $rates;
}

// Enqueue custom JavaScript
function enqueue_custom_shipping_scripts() {
if (is_checkout()) {
wp_enqueue_script('custom-shipping-js', plugin_dir_url(__FILE__) . 'custom-shipping.js', array('jquery', 'wc-checkout'), '1.0', true);
wp_localize_script('custom-shipping-js', 'customShippingParams', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
}
add_action('wp_enqueue_scripts', 'enqueue_custom_shipping_scripts');

// Handle AJAX request to update shipping cost
add_action('wp_ajax_update_shipping_cost', 'update_shipping_cost');
add_action('wp_ajax_nopriv_update_shipping_cost', 'update_shipping_cost');

function update_shipping_cost() {
if (isset($_POST['payment_method'])) {
WC()->session->set('chosen_payment_method', sanitize_text_field($_POST['payment_method']));

}
WC()->cart->calculate_totals();
WC()->cart->maybe_set_cart_cookies();

wp_send_json_success();
}
custom-shipping.js

Код: Выделить всё

jQuery(document).ready(function($) {
// Detect changes in payment method selection
$('form.checkout').on('change', 'input[name="payment_method"]', function() {
var paymentMethod = $(this).val();
console.log("Selected Payment Method: " + paymentMethod); // Log selected payment method
// Update session and trigger checkout update via AJAX
$.ajax({
type: 'POST',
url: customShippingParams.ajax_url,
data: {
action: 'update_shipping_cost',
payment_method: paymentMethod,
},
success: function(response) {
console.log("AJAX Response: ", response); // Log the response
if (response.success) {
console.log('Success');
// Trigger WooCommerce update checkout event
$(document.body).trigger('update_checkout');
// location.reload(true);
}
},
error: function(error) {
console.error('AJAX error:', error); // Debugging
}
});
});

// Prevent the 'update_checkout' event from being triggered infinitely
var isUpdating = false;
$(document.body).on('update_checkout', function() {
if (!isUpdating) {
isUpdating = true;
$('body').trigger('update_checkout');
isUpdating = false;
}
});
});
Что я делаю не так?

Подробнее здесь: https://stackoverflow.com/questions/785 ... ent-method
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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