[转]wordpress 基于用户角色改变woocommerce显示价格

问题描述

我希望根据用户角色(批发商,经销商等)和根据该类别显示不同的价格。

有一个动态定价插件,一旦项目被添加到购物车,而不是页面本身,显示这些折扣。

有没有办法使用过滤器或动作检查用户级别,检查项目的类别,然后动态更改价格?

最佳解决方案

是的,您可以使用woocommerce_get_price过滤器钩子根据用户角色过滤值,并相应地返回价格,例如:

add_filter('woocommerce_get_price', 'custom_price_WPA111772', 10, 2);
/**
 * custom_price_WPA111772
 *
 * filter the price based on category and user role
 * @param $price
 * @param $product
 * @return
 */
function custom_price_WPA111772($price, $product) {
 if (!is_user_logged_in()) return $price;

//check if the product is in a category you want, let say shirts
 if( has_term( 'shirts', 'product_cat' ,$product->ID) ) {
 //check if the user has a role of dealer using a helper function, see bellow
 if (has_role_WPA111772('dealer')){
 //give user 10% of
 $price = $price * 0.9;
 }
 }
 return $price;
}

/**
 * has_role_WPA111772
 *
 * function to check if a user has a specific role
 *
 * @param string $role role to check against
 * @param int $user_id user id
 * @return boolean
 */
function has_role_WPA111772($role = '',$user_id = null){
 if ( is_numeric( $user_id ) )
 $user = get_user_by( 'id',$user_id );
 else
 $user = wp_get_current_user();

if ( empty( $user ) )
 return false;

return in_array( $role, (array) $user->roles );
}

我这边测试的时候没有解决我的问题,可能造成这个原因是多方面的,我们不妨使用插件来协助我们解决,这里推荐这么一个插件:

Customer Specific Pricing for WooCommerce

这个插件可以设定同一个产品给不同用户提供不同的价格。功能截图如下:

未经允许不得转载:哈勃私语 » [转]wordpress 基于用户角色改变woocommerce显示价格

本文共1155个字 创建时间:2017年11月9日15:59   

分享到:更多 ()