Dynamically add fees based on selected payment gateway in WooCommerce
<?php
function yanco_scripts() {
if( !is_admin() ) {
wp_register_script( 'yanco-child-theme-script', get_stylesheet_directory_uri() . '/assets/js/child-theme-functions.js', array('jquery'), null );
if( is_checkout() ) {
wp_enqueue_script( 'yanco-child-theme-script' );
}
}
}
add_action( 'wp_enqueue_scripts', 'yanco_scripts' );
if ( class_exists( 'WooCommerce' ) ) {
add_action( 'woocommerce_cart_calculate_fees', 'yanco_ean_calculate_totals' );
function yanco_ean_calculate_totals( ) {
$available_gateways = WC()->payment_gateways->get_available_payment_gateways();
$current_gateway = '';
$fee_title = 'EAN Ekspeditionsgebyr';
if ( ! empty( $available_gateways ) ) {
// Chosen Method
if ( isset( WC()->session->chosen_payment_method ) && isset( $available_gateways[ WC()->session->chosen_payment_method ] ) ) {
$current_gateway = $available_gateways[ WC()->session->chosen_payment_method ];
} elseif ( isset( $available_gateways[ get_option( 'woocommerce_default_gateway' ) ] ) ) {
$current_gateway = $available_gateways[ get_option( 'woocommerce_default_gateway' ) ];
} else {
$current_gateway = current( $available_gateways );
}
}
if ( $current_gateway->id == 'yanco_wc_ean_payment_gateway' ) {
WC()->cart->add_fee( $fee_title, 50*0.8 , true, '' );
}
}
}
jQuery(document).ready(function() {
jQuery(document.body).on('change', 'input[name="payment_method"]', function() {
jQuery('body').trigger('update_checkout');
});
});