V functions.php naslednja koda. Pomembno je, da se checkout osveži po spremembi parametrov (zaradi izračuna):
//1
add_action('woocommerce_cart_calculate_fees', 'add_cod_fee_based_on_shipping', 20, 1);
function add_cod_fee_based_on_shipping($cart) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
// Check if COD is selected
if (WC()->session->get('chosen_payment_method') === 'cod') {
// Get the chosen shipping method
$chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
if ($chosen_shipping_methods) {
$chosen_shipping = explode(':', $chosen_shipping_methods[0])[0]; // Extract method (ignoring instance id)
// Apply only for shipping, not local pickup
if ($chosen_shipping !== 'local_pickup') {
// Add a €2 fee for COD
WC()->cart->add_fee(__('Plačilo po povzetju', 'your-text-domain'), 2);
}
}
}
}
//2
add_action('woocommerce_cart_calculate_fees', 'add_leanpay_fee', 20, 1);
function add_leanpay_fee($cart) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
// Check if Leanpay is selected
if (WC()->session->get('chosen_payment_method') === 'wc_leanpay_module') {
// Add a €5 fee for Leanpay
WC()->cart->add_fee(__('Stroški obdelave Leanpay', 'your-text-domain'), 5);
}
}
//3
add_action('wp_enqueue_scripts', 'refresh_checkout_on_change');
function refresh_checkout_on_change() {
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(function($){
// Trigger update when payment method is changed
$('form.woocommerce-checkout').on('change', 'input[name="payment_method"]', function() {
$('body').trigger('update_checkout');
});
// Trigger update when shipping method is changed
$('form.woocommerce-checkout').on('change', 'input.shipping_method', function() {
$('body').trigger('update_checkout');
});
});
</script>
<?php
}
}
//4
add_filter('woocommerce_package_rates', 'hide_shipping_when_free_is_available', 100, 2);
function hide_shipping_when_free_is_available($rates, $package) {
$free = array();
$local_pickup = array();
foreach ($rates as $rate_id => $rate) {
// Check if it's free shipping
if ('free_shipping' === $rate->method_id) {
$free[$rate_id] = $rate;
}
// Always keep local pickup
if ('local_pickup' === $rate->method_id) {
$local_pickup[$rate_id] = $rate;
}
}
// If free shipping is available, return only free shipping and local pickup
return !empty($free) ? array_merge($free, $local_pickup) : $rates;
}
//5
add_action('wp_footer', 'refresh_checkout_on_payment_method_change');
function refresh_checkout_on_payment_method_change() {
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(function($) {
// Trigger the WooCommerce checkout update when payment method is changed
$('form.woocommerce-checkout').on('change', 'input[name="payment_method"]', function() {
$('body').trigger('update_checkout');
});
});
</script>
<?php
}
}