Show hide payment gateways based on backordered items in Woocommerce

倖福魔咒の 提交于 2020-06-26 14:05:32

问题


I'm need to hide paypal when there's any backordered item on cart or hide cod if there's not any item to be backordered. My problem here is if there's a item that's backorder together with one that is not, I end up whitout a payment processor

 add_filter( 'woocommerce_available_payment_gateways', 'backordered_items_hide_cod', 90, 1 );
function backordered_items_hide_cod( $available_gateways ) {
    // Only on front end
    if ( is_admin() )
        return;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ){
        if( $cart_item['data']->is_on_backorder( $cart_item['quantity'] ) ) {
            // Hide payment gateway
            unset($available_gateways['paypal']);
            } else {
            unset($available_gateways['cod']);
            break; // Stop the loop
        }
    }

    return $available_gateways;
}

回答1:


The following function will hide paypal for any backordered item found or if there is no backordered items it will hide COD instead:

add_filter( 'woocommerce_available_payment_gateways', 'backordered_items_hide_cod', 90, 1 );
function backordered_items_hide_cod( $available_gateways ) {
    // Not in backend (admin)
    if( is_admin() ) 
        return $available_gateways;

    $has_a_backorder = false;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ){
        if( $cart_item['data']->is_on_backorder( $cart_item['quantity'] ) ) {
            $has_a_backorder = true;
            break;
        } 
    }

    if( $has_a_backorder ) {
        unset($available_gateways['paypal']);
    } else {
        unset($available_gateways['cod']);
    }

    return $available_gateways;
}

Code goes in functions.php file of your active child theme (active theme). Tested and works.



来源:https://stackoverflow.com/questions/53131507/show-hide-payment-gateways-based-on-backordered-items-in-woocommerce

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