我已经设置了一个自定义用户角色,其名称为
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 )){
的每一行给出了此错误。
我猜这与上面代码的第 5 行有关,我使用错误:警告:
期望参数 2 为数组,在...中给出 nullin_array()
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+ 进行了测试……现在应该可以工作了……