在WooCommerce中为特定类别的最便宜商品打折 [英] Discounting the cheapest item for a specific category in WooCommerce
问题描述
我想根据产品类别对Woocommerce中最便宜的购物车产品打折.根据"产品的购物车折扣在Woocommerce中价格更低" 效果很好的答案代码.
I wound like to discount the cheapest cart item in Woocommerce, based on a product category. Based on "Cart discount for product that cost less in Woocommerce" answer code that works perfectly.
但是如何使其仅适用于特定产品类别.
But how to make it work for a specific product category only.
这个想法是在购物车中有2种商品,并且针对特定商品类别的最便宜商品有折扣.
The idea is to have 2 products in the shopping cart and have a discount on the cheapest item for a specific product category.
推荐答案
已更新-仅限已定义产品类别中的2个项目.
Updated - Limiting to 2 items from the defined product category.
以下将对特定产品类别(将在代码中定义)执行相同的操作:
The following will do the same for a specific product category (to be defined in the code):
add_action('woocommerce_cart_calculate_fees', 'discount_on_cheapest_cart_item', 20, 1 );
function discount_on_cheapest_cart_item( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Settings
$categories = ['tshirts']; // Your product categories (coma separated)
$percentage = 10; // 10 % discount
// Only for 2 items or more
if ( $cart->get_cart_contents_count() < 2 ) return;
// Initialising
$discount = 0;
$item_prices = array();
// Loop though each cart items and set prices in an array
foreach ( $cart->get_cart() as $cart_item ) {
if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] );
}
}
// We set the fee for 2 items of the defined product category
if( count($product_prices_excl_tax) == 2 ) {
sort($product_prices_excl_tax);
$discount = reset($product_prices_excl_tax) * $percentage / 100;
$cart->add_fee( sprintf( __("Discount on cheapest %s"), '('.$percentage.'%)' ), -$discount );
}
}
代码进入您的活动子主题(或活动主题)的function.php文件中.应该可以.
Code goes in function.php file of your active child theme (or active theme). It should works.
这篇关于在WooCommerce中为特定类别的最便宜商品打折的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!