我正在我的 Wordpress 商店中开发动态定价系统。我已经设置了它,以便具有某些角色的用户(现在是订阅者或管理员 - 用于测试目的)获得 15% 的折扣(价格*0.85)。但是,我还需要从折扣规则中排除特定的产品类别。
现在我有:
function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
//if admin || subscriber
$role = get_user_role(); /* I know that isn't the default get user role. I made a shortened version of it in functions.php because I used it a lot in other functions */
if (in_array("admin", $role) || in_array("subscriber", $role)){
$product = wc_get_product( $product_id );
// ==> Start: Needed product category check HERE
$price = $product->get_price();
$cart_item_data['RefPrice'] = $price * 0.85;
// ==> End of product category check
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 2 );
function before_calculate_totals( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Iterate through each cart item
foreach( $cart_obj->get_cart() as $key=>$value ) {
if( isset( $value['RefPrice'] ) ) {
$price = $value['RefPrice'];
$value['data']->set_price( ( $price ) );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals', 10, 1 );
这正在努力通过
* 0.85
修改某些角色的价格,但我在尝试从中排除产品类别时遇到了困难。产品类别 ID 为 978(或其名称为“最后一刻礼物”)。
如何为每个购物车项目添加此支票?
更新…这是从自定义动态定价中排除产品类别的方法,对第一个挂钩函数进行一些小更改。
has_term()
WordPress 条件函数来排除产品类别,这样:
function get_user_roles(){
global $current_user;
return $current_user->roles;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 2 );
function add_cart_item_data( $cart_item_data, $product_id ) {
//if admin || subscriber
$roles = get_user_roles();
if (in_array('administrator', $roles) || in_array('subscriber', $roles)){
// Excluded product categories in this array (Can be IDs, slugs or names)
$excl_cats = array( 978 );
$product = wc_get_product( $product_id );
// Excluding product categories
if( ! has_term( $excl_cats, 'product_cat', $product_id ) ){
$cart_item_data['ref_price'] = $product->get_price() * 0.85;
// Every add to cart action is set as a unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
}
return $cart_item_data;
}
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals', 10, 1 );
function before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {
if( isset( $cart_item['ref_price'] ) ) {
$cart_item['data']->set_price( floatval($cart_item['ref_price']) );
}
}
}
代码位于活动子主题(或活动主题)的 function.php 文件中。
已测试且有效