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

Error when adding product with custom pricing to cart - WooCommerce

我已经设置了一个带有 performance_customer 的自定义用户角色。我正在检查当前用户是否是 "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 )){.

的每一行都给出了这个错误

Error: Warning: in_array() expects parameter 2 to be array, null given in…

我猜这与上面代码的第 5 行有关,我在其中使用 wp_get_post_terms() 形成每个产品所属类别的数组。我不确定如何进行这项工作。

首先,过滤器钩子 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+ 进行测试……现在应该可以使用了……