Code-Snippets-Functions/Execute a function on a child site/WooCommerce/set-product-price-according-to-payment-method-in-checkout.txt
2023-07-14 12:40:28 -06:00

26 lines
1.1 KiB
Text

add_action('woocommerce_before_calculate_totals', 'update_product_prices_and_totals' );
function update_product_prices_and_totals( $cart ) {
if ( is_admin() && ! defined('DOING_AJAX') )
return;
if ( is_checkout() && ! is_wc_endpoint_url() && WC()->session->get('chosen_payment_method') === 'invoice') {
// Define here the array of targeted product IDs
$targeted_ids = array(338991, 353754);
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Check for the targeted product (IDs) to be changed
if ( in_array($cart_item['product_id'], $targeted_ids) || in_array($cart_item['variation_id'], $targeted_ids) ) {
$cart_item['data']->set_price(0); // Set the price to 0
}
}
}
}
// Refresh checkout on payment method change.
add_action('woocommerce_checkout_init', 'payment_methods_trigger_update_checkout');
function payment_methods_trigger_update_checkout() {
wc_enqueue_js("$('form.checkout').on('change', 'input[name=payment_method]', function() {
$(document.body).trigger('update_checkout');
});");
}