Woocommerce 一个类别的商业折扣
我想为一个类别中的所有产品添加折扣。我在这里尝试过这个函数:Woocommerce 一个类别的商业折扣,woocommerce,Woocommerce,我想为一个类别中的所有产品添加折扣。我在这里尝试过这个函数: 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 $pr
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()
:
它工作得非常完美,我在单个产品页面、购物车小部件、购物车页面、结帐页面和订单中都看到了折扣。但是,当我尝试设置某个类别中某个特定产品的折扣时,该产品会以正常价格添加到购物车中,并且没有折扣
我也尝试在这里使用:
get_the_terms( $product->ID, 'product_cat' );
然后创建类别数组并使用以下方法:
if ( in_array( 'promocje-i-outlet', $kategoria ) ) {
$price = $price * ( 1 - 0.25 );
}
但效果是一样的——动态定价不起作用,我得到了以下警告:
警告:in_array()要求参数2为数组,如果给定空值
我做错了什么?我不是100%确定,但这不能工作,因为这是一个在页面构建期间循环所有产品的函数。
has_term
功能在此处无法工作,因为它仅在您处于特定的单个产品页面时工作
请尝试以下方法:
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;
}
请告诉我它是否有效。太好了:)如果对你有帮助,也许你可以接受我的答案。@LoicTheAztec哦,我不知道。我来换钩子!
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;
}