[英]Apply/determine discount based on a particular product category only when a specific product is in WooCommerce cart
我想復制特定項目的促銷。
如果您購買一件 (b10 plus) 產品,那么您有資格在所有塑光工具上享受總計 289 歐元的折扣,因此,如果您將 100 歐元的“類別小計”添加到購物車配件,您將獲得 100 歐元的折扣,如果您購買 300 歐元的配件,您可以獲得 289 歐元的折扣。
我嘗試了另一種解決方案(插件和 php 代碼),但它一直以 289 美元的價格為每個項目(對應於“配件”)打折。
如果“B10 plus”在購物車中,我還嘗試自動包含該類別的折扣。 但此代碼將折扣添加到單個產品
這是我當前的代碼:
add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );
function bbloomer_apply_matched_coupons() {
$coupon_code = 'promob10';
if ( WC()->cart->has_discount( $coupon_code ) ) return;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// this is your product ID
$autocoupon = array( 373 );
if ( in_array( $cart_item['product_id'], $autocoupon ) ) {
WC()->cart->apply_coupon( $coupon_code );
wc_print_notices();
}
}
}
要根據特定產品 ID 應用折扣,您可以使用woocommerce_cart_calculate_fees
掛鈎
所以你得到:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Product ID of the specific product
$specific_product_id = 817;
// The term name/term_id/slug to check for.
$category = 'accessories';
// Initialize
$total_discount = 0;
$maximum_discount = 0;
// Cart id
$product_cart_id = $cart->generate_cart_id( $specific_product_id );
// Find product in cart
$in_cart = $cart->find_product_in_cart( $product_cart_id );
// In cart
if ( $in_cart ) {
// Gets cart contents
foreach ( $cart->get_cart_contents() as $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// Compare
if ( $product_id == $specific_product_id ) {
// Get price = maximum discount
$maximum_discount = $cart_item['data']->get_price();
}
// Has certain category
if ( has_term( $category, 'product_cat', $product_id ) ) {
// Get price
$price = $cart_item['data']->get_price();
// Get quantity
$quantity = $cart_item['quantity'];
// Addition to the total discount
$total_discount += $price * $quantity;
}
}
// Less than
if ( $total_discount < $maximum_discount ) {
// Add total discount
$cart->add_fee( __( 'Discount applied', 'woocommerce' ), -$total_discount, false );
} else {
// Add maximum discount
$cart->add_fee( __( 'Discount applied', 'woocommerce' ), -$maximum_discount, false );
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.