将具有自定义定价的产品添加到购物车时出错 - WooCommerce

问题描述 投票:0回答:1

我已经设置了一个自定义用户角色,其名称为

performance_customer
。我正在检查当前用户是否是“绩效客户”,并对特定类别的产品应用一定的价格折扣。

这是我的代码:

function return_custom_performance_dealer_price($price, $product) {

    global $woocommerce;
    global $post;
    $terms = wp_get_post_terms( $post->ID, 'product_cat' );
    foreach ( $terms as $term ) $categories[] = $term->slug;

    $origPrice = get_post_meta( get_the_ID(), '_regular_price', true);
    $price = $origPrice;

    //check if user role is performance dealer
    $current_user = wp_get_current_user();
    if( in_array('performance_customer', $current_user->roles)){
        //if is category performance hard parts
        if(in_array( 'new-hard-parts-150', $categories )){
            $price = $origPrice * .85;
        }
        //if is category performance clutches
        elseif(in_array( 'performance-clutches-and-clutch-packs-150', $categories )){
            $price = $origPrice * .75;
        }
        //if is any other category
        else{
            $price = $origPrice * .9;
        }
    }
    return $price;
}
add_filter('woocommerce_get_price', 'return_custom_performance_dealer_price', 10, 2);

该函数在产品循环中完美运行,但是当我将产品添加到购物车时,它爆炸了,并为包含

if(in_array( 'CATEGORY_NAME_HERE', $categories )){
的每一行给出了此错误。

错误:警告:

in_array()
期望参数 2 为数组,在...中给出 null

我猜这与上面代码的第 5 行有关,我使用

wp_get_post_terms()

 来形成每个产品所属类别的数组。我不知道如何进行这项工作。 

php wordpress woocommerce cart product-price
1个回答
1
投票
首先,过滤器钩子

woocommerce_product_get_price

现在正在取代已弃用的钩子woocommerce_get_price

为了避免出现错误,您应该使用Wordpress条件专用功能

has_term()



我重新审视了你的代码,所以请尝试这个:

add_filter('woocommerce_product_get_price', 'return_custom_performance_dealer_price', 10, 2); function return_custom_performance_dealer_price( $price, $product ) { $price = $product->get_regular_price(); //check if user role is performance dealer $current_user = wp_get_current_user(); if( in_array('performance_customer', $current_user->roles) ){ //if is category performance hard parts if( has_term( 'new-hard-parts-150', 'product_cat', $product->get_id() ) ){ $price *= .85; } //if is category performance clutches elseif( has_term( 'performance-clutches-and-clutch-packs-150', 'product_cat', $product->get_id() ) ){ $price *= .75; } //if is any other category else{ $price *= .9; } } return $price; }

代码位于活动子主题(或主题)的 function.php 文件中,或者也位于任何插件文件中。

针对 WooCommerce 3+ 进行了测试……现在应该可以工作了……

© www.soinside.com 2019 - 2024. All rights reserved.