【问题标题】:Woocommerce discount for one category一类的 Woocommerce 折扣
【发布时间】:2019-02-15 09:07:43
【问题描述】:

我想为一个类别中的所有产品添加折扣。我在这里试过这个功能:

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() 的情况下使用这个时:

$price = $price * ( 1 - 0.25 );

效果很好,我可以在单个产品页面、购物车小部件、购物车页面、结帐页面和订单中看到折扣。但是,当我尝试为某个类别中的特定产品设置折扣时,该产品会以正常价格添加到购物车中,而没有折扣。

我也尝试在这里使用它:

get_the_terms( $product->ID, 'product_cat' );

然后制作类别数组并使用它:

if ( in_array( 'promocje-i-outlet', $kategoria ) ) {
    $price = $price * ( 1 - 0.25 );
}

但效果是一样的 - 动态定价不起作用,我收到以下警告:

警告:in_array() 期望参数 2 为数组,给定为空

我做错了什么?

【问题讨论】:

    标签: woocommerce


    【解决方案1】:

    我不能 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 哦,我不知道。我会换钩的!
    猜你喜欢
    • 2018-02-26
    • 2018-03-08
    • 2014-02-12
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2019-08-28
    • 2021-08-09
    相关资源
    最近更新 更多