一个类别的 Woocommerce 折扣 [英] Woocommerce discount for one category
问题描述
我想为一个类别中的所有产品添加折扣.我在这里试过这个功能:
I want to add a discount for all products in a category. I've tried this function here:
add_filter( 'woocommerce_get_price', 'custom_price_sale', 10, 2 );
function custom_price_sale( $price, $product ) {
if ( has_term( 'promocje-i-outlet', 'product_cat' ) ) {
$price = $price * ( 1 - 0.25 );
}
return $price;
}
当我只使用这个而不使用 if()
时:
When I'm using just this without the if()
:
$price = $price * ( 1 - 0.25 );
它运行良好,我在单个产品页面、购物车小部件、购物车页面、结帐页面和订单中看到了折扣.但是,当我尝试为类别中的特定产品设置折扣时,该产品会以正常价格添加到购物车中,但没有折扣.
it works perfectly and I see the discount on the single product page, in cart widget, on cart page, on checkout page and in an order. But when I try to set the discount to a specific product in a category, the product get's added to cart with regular price and without the discount.
我也试过在这里使用它:
I've also tried to use this here:
get_the_terms( $product->ID, 'product_cat' );
然后制作类别数组并使用它:
Then make array of categories and use this:
if ( in_array( 'promocje-i-outlet', $kategoria ) ) {
$price = $price * ( 1 - 0.25 );
}
但效果是一样的 - 动态定价不起作用,我收到了这个警告:
But the effect is the same - dynamic pricing isn't working and I get this warning:
警告:in_array() 期望参数 2 为数组,给定为空
我做错了什么?
推荐答案
我不是 100% 肯定,但这行不通,因为这是在页面构建期间循环所有产品的函数中.has_term
函数在此处不起作用,因为它仅在您位于特定的单一产品页面上时起作用.
I'm not 100% sure but this can't work because this is within a function which loops over all products during the page build. The has_term
function can't work here because it only works when you're on a specific single-product page.
在这里试试这个:
add_filter( 'woocommerce_product_get_price', 'custom_sale_price_for_category', 10, 2 );
function custom_sale_price_for_category( $price, $product ) {
//Get all product categories for the current product
$terms = wp_get_post_terms( $product->get_id(), 'product_cat' );
foreach ( $terms as $term ) {
$categories[] = $term->slug;
}
if ( ! empty( $categories ) && in_array( 'promocje-i-outlet', $categories, true ) ) {
$price *= ( 1 - 0.25 );
}
return $price;
}
请告诉我它是否有效.
这篇关于一个类别的 Woocommerce 折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!