我想根据用户角色“clubmember”和元框“clubmember_price”中填写的百分比来显示和应用产品百分比折扣。
我使用下面的代码来获得百分比折扣(在购物车上,而不是在产品上),效果很好。
/* discount clubmembers */
add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role', 20, 1 );
function discount_based_on_user_role( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return; // Exit
// only for 'clubmember' role
if ( ! current_user_can('clubmember') )
return; // Exit
// Kortings percentage
$percentage = 10
$discount = $cart->get_subtotal() * $percentage / 100; // Calculation
// Applying discount
$cart->add_fee( sprintf( __("Clubmember discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}
结账时显示“会员折扣”的信息,看起来不错。我现在的问题是,上面的代码对总购物车应用折扣。
我想要产品本身的折扣,但前提是填充了元框“clubmember_price”。为此,我用以下代码替换了代码:
/* Custom prices by user role */
add_filter('woocommerce_product_get_price', 'custom_price_assign', 10, 2);
add_filter('woocommerce_product_variation_get_price', 'custom_price_assign', 10, 2); // For product variations (optional)
function custom_price_assign( $price, $product ) {
// Check if the user has a role of wholesaler
if ( current_user_can('clubmember') && $clubmember_price = $product->get_meta('clubmember_price') ){
return $price * (100 - $clubmember_price) / 100;
}
return $price;
}
现在的问题是,我在任何地方都看不到折扣。因此,用户不会看到他们有“降低”的价格,该代码片段只是更改了价格。
我想显示正常价格,并在产品页面、购物车/结帐上显示折扣。
我尝试以任何方式组合这两个代码,但由于我是 PHP 新手,我无法让它工作。我感觉我需要在两个函数之间使用“if”,但我不知道如何或是否可以这样做。
我真的很想了解它是如何工作的,并能够在将来自己编写这些片段。如果有人能解释我错过了什么,那就太好了!
要根据特定用户角色在产品级别提供可见折扣,您需要添加以下内容以制定促销价格:
add_filter('woocommerce_product_get_sale_price', 'custom_sale_price_assign', 10, 2);
add_filter('woocommerce_product_variation_get_sale_price', 'custom_sale_price_assign', 10, 2);
function custom_sale_price_assign( $price, $product ) {
// Check if the user has a role of wholesaler
if ( current_user_can('clubmember') && $product->get_meta('clubmember_price') ){
$price = $product->get_price();
}
return $price;
}
现在所有相关“俱乐部会员”折扣产品价格都将进行促销,显示旧价格金额(划掉),以及新折扣价格。
然后,按照这些线程(和其他),您将能够按照您的意愿自定义内容,例如还显示每个“俱乐部成员”的折扣百分比或节省金额,以及一些自定义文本产品价格折扣。