Monday, 9 June 2025

Shipping cost apply base on cart total using hooks in wordpress

 add_action('woocommerce_cart_calculate_fees', 'custom_shipping_fee_based_on_cart_total', 10, 1);


function custom_shipping_fee_based_on_cart_total($cart) {

    // Ensure WooCommerce is initialized and cart is available

    if (is_admin() && !defined('DOING_AJAX')) {

        return;

    }


    $cart_total = $cart->get_cart_contents_total(); // Get cart subtotal


    // Example logic:

    // - Cart total under ₹500: Add ₹50 shipping

    // - Cart total ₹500 - ₹1000: Add ₹30 shipping

    // - Cart total ₹1000 or more: Free shipping


    if ($cart_total < 500) {

        $shipping_fee = 50;

    } elseif ($cart_total < 1000) {

        $shipping_fee = 30;

    } else {

        $shipping_fee = 0;

    }


    // Add fee if greater than 0

    if ($shipping_fee > 0) {

        $cart->add_fee(__('Shipping Fee', 'your-textdomain'), $shipping_fee, false);

    }

}