[Solved] How can I restrict the Cash on Delivery payment method to specific product categories in WooCommerce?

  

3
Topic starter

I have a WooCommerce e-store and for a particular category (e-books) I want to the remove the Cash on Delivery (cod) payment method.

How can I do it with a code in functions.php?

Thanks, sam!

1 Answer
2

Here is the code my friend (put it in functions.php in your Child Theme):

function custom_payment_gateway_for_product_category($available_gateways) {
    if (is_admin()) return $available_gateways;

    // Define the product category or tag ID
    $target_category = 'example-category'; // Replace with your category slug

    // Get the items in the cart
    foreach (WC()->cart->get_cart() as $cart_item) {
        $product_id = $cart_item['product_id'];

        // Check if the product belongs to the target category
        if (has_term($target_category, 'product_cat', $product_id)) {
            // Allow only specific payment gateway(s) and disable others
            unset($available_gateways['cod']); // Disable Cash on Delivery (COD)
            // You can unset other gateways similarly, if needed
        }
    }

    return $available_gateways;
}

add_filter('woocommerce_available_payment_gateways', 'custom_payment_gateway_for_product_category');
Share: