Null cart item price for a specific product category in Woocommerce

老子叫甜甜 提交于 2019-12-12 04:15:48

问题


I want to remove / takeout the price of a specific category products from Cart Total.

Please see this screenshot:

What hook could I use to do this?

Thanks.


回答1:


The right hook to do that is woocommerce_before_calculate_totals using has_term() WordPress conditional function to filter product categories in cart items. This way you can null the price for that cart items.

This is the code (added compatibility for Woocommerce 3+):

add_action( 'woocommerce_before_calculate_totals', 'custom_price_product_category', 20, 1 );
function custom_price_product_category( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        // When a product has 'glass' as category we null the price.
        if( has_term( 'glass', 'product_cat', $cart_item["product_id"] ) ){
            // Added Woocommerce 3+ compatibility
            if( version_compare( WC_VERSION, '3.0', '<' ) )
                $item['data']->price = '0';
            else
                $item['data']->set_price(0);
        }
    }
}

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

This code is tested and works.



来源:https://stackoverflow.com/questions/40572277/null-cart-item-price-for-a-specific-product-category-in-woocommerce

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