How to disable Cash on Delivery on some specific products in Woocommerce

心已入冬 提交于 2019-12-19 05:09:42

问题


I want to disable Cash on Delivery(COD) for some products on my online shopping site.

Is it Possible?


回答1:


Compatible with woocommerce version 3+

Based on "Disable all payments gateway if there's specifics products in the Cart".

The code:

add_filter( 'woocommerce_available_payment_gateways', 'conditionally_disable_cod_payment_method', 10, 1);
function conditionally_disable_cod_payment_method( $gateways ){
    // HERE define your Products IDs
    $products_ids = array(37,40,53);

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ){
        // Compatibility with WC 3+
        $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
        if (in_array( $cart_item['product_id'], $products_ids ) ){
            unset($gateways['cod']);
            break; // As "COD" is removed we stop the loop
        }
    }
    return $gateways;
}

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

Tested and works




回答2:


To do this you have to use woocommerce_available_payment_gateways filter.

add_filter('woocommerce_available_payment_gateways', 'show_hide_cod', 10, 1);

function show_hide_cod($gateways)
{
    //list of product id to exclude COD
    $product_id_list = [12, 34];
    $items = WC()->cart->get_cart();
    foreach ($items as $item => $values)
    {
        $_product = $values['data']->post;
        if (in_array($_product->ID, $product_id_list))
        {
            unset($gateways['cod']);
        }
    }
    return $gateways;
}

Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Please Note: I have't tested this code.



来源:https://stackoverflow.com/questions/42108036/how-to-disable-cash-on-delivery-on-some-specific-products-in-woocommerce

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