Programmatically change Payment Methods WooCommerce

The question:

I am trying to programmatically manipulate the selection of Payment Method between BACS and a No Payment required option. My client wants the ability to Request for Quote only, so I’ve extended woocommerce actions and filters, and provided a method to request quote through the cart system. If the user has requested a quote only, on the checkout page I am trying to auto select the Cash on Delivery option, which I’ve renamed to “Request for Quote Only – No payment required”. Any advice would be helpful.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Theres a filter called woocommerce_available_payment_gateways:

add_filter('woocommerce_available_payment_gateways','filter_gateways',1);
function filter_gateways($gateways){
    global $woocommerce;        
    //Remove a specific payment option
    unset($gateways['paypal']);
    return $gateways;
}

I’m not sure where and how you get / store the Request for Quote option, but you can access the value inside the filter_gateways function and you can remove a specific gateway with a conditional logic.

Method 2

My problem here was with using query vars to store a value to indicate that the request is for quote only. The payment area is dynamically refreshed based on changes within the checkout areas, and on load, payment methods is reloaded, and query var values are lost. I managed to overcome this issue by making use of the WC()->session->set and WC()->session->get functions. I’ve added the following two actions to manipulate layout based on the session value.

add_action("woocommerce_before_checkout_form", "custom_before_checkout_action");
function custom_before_checkout_action() {
    if (isset($_GET["quote"]) && $_GET["quote"] == "1") {
        echo '<h2>Request for Quote</h2>';
        WC()->session->set("quote","true");
    }
    else {
        WC()->session->set("quote","false");
        echo '<h2>Buy Sample</h2>';
    }
}

add_filter('woocommerce_available_payment_gateways','filter_gateways',1);
function filter_gateways($gateways){
    if (WC()->session->get("quote") == "true")
        unset($gateways['bacs']);
    else
        unset($gateways['cod']);

    return $gateways;
}

This seems to do the trick to preserve the value, and add conditional logic even after the payment area reloads.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment