问题
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