Conditionally hiding et showing payment gateways

浪尽此生 提交于 2019-12-11 04:49:55

问题


In Woocommerce, I would like to hide "paypal" gateway on the "checkout" page before the order is created for the first time and just show "cash on delivery" gateway (labeled as Reserve).

On the other hand, on checkout/order-pay page when the order status is "pending", hide the 'Reserve' gateway and show "paypal". (this happens when we change the status of the order to "pending" manually and send the invoice to the customer with a payment link).

I thought it should be done by checking order status and using the woocommerce_available_payment_gateways filter hook. But I have problems with getting current order status.

Also I'm not sure what's the status of a newly created order which the user is on the checkout page and still the order is not shown in the admin backend.

This is my incomplete code:

function myFunction( $available_gateways ) {

    // How to check if the order's status is not pending payment?
    // How to pass the id of the current order to wc_get_order()?
     $order = wc_get_order($order_id); 

    if ( isset($available_gateways['cod']) && /* pending order status?? */ ) { 
        // hide "cod" gateway
    } else {
        // hide "paypal" gateway
    }
    return $available_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'myFunction' );

I also tried WC()->query_vars['order'] instead of wc_get_order(); to get the current order and check its status but it didn't work too.

I saw woocommerce_order_items_table action hook but couldn't get the order either.

How could I retrieve the Id and the status of the order on the checkout/order-pay page?


回答1:


If I have correctly understood, You want to set/unset your available payment gateways, depending on the live generated order which status has to pending to have the "paypal" gateway. Ian all other cases the available gateway is only "reserve" (renamed "cod" payment gateway).

This code retrieve this live order ID using the $_SERVER['REQUEST_URI'], this way:

add_filter( 'woocommerce_available_payment_gateways', 'custom_available_payment_gateways' );
function custom_available_payment_gateways( $gateways ) {

    $url_arr = explode('/', $_SERVER['REQUEST_URI']);
    if($url_arr[1] == 'checkout' && $url_arr[2] == 'order-pay' && is_user_logged_in() ){
        $order_id = intval($url_arr[3]);
        $order = wc_get_order($order_id);
        if( $order->has_status('pending') )
            unset( $gateways['cod'] );
        else
            unset( $gateways['paypal'] );
    } else
        unset( $gateways['paypal'] );

    return $gateways;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

The code is tested and works.



来源:https://stackoverflow.com/questions/42513500/conditionally-hiding-et-showing-payment-gateways

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!