如何在WooCommerce商品页显示基于用户角色的折扣
如何在WooCommerce商品页显示基于用户角色的对应折扣
当然可以在商品页显示对应角色的折扣,下面先优化你当前的购物车折扣代码(原代码存在逻辑缺陷,每个角色判断后若不满足直接终止函数,无法匹配后续角色),再添加商品页显示折扣的实现代码:
一、优化后的购物车折扣代码
// 经销商多档折扣 - 购物车应用 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; // 定义角色与折扣率对应关系 $role_discounts = array( 'wcwp_reseller_45' => 45, 'wcwp_reseller_40' => 40, 'wcwp_reseller_35' => 35, 'wcwp_reseller_30' => 30, 'wcwp_reseller_25' => 25, 'wcwp_reseller_20' => 20, 'wcwp_reseller_15' => 15, 'wcwp_reseller_10' => 10, ); $user = wp_get_current_user(); $applied_discount = 0; // 遍历角色,匹配用户对应的最高折扣率 foreach ( $role_discounts as $role => $percentage ) { if ( in_array( $role, $user->roles ) ) { $applied_discount = $percentage; break; // 取最高优先级的折扣(按数组顺序,前面的角色折扣更高) } } // 若匹配到折扣,计算并添加优惠 if ( $applied_discount > 0 ) { $discount = $cart->get_subtotal() * $applied_discount / 100; $cart->add_fee( sprintf( __( "折扣 (%s)", "woocommerce" ), $applied_discount . '%'), -$discount, true ); } }
二、商品页显示对应折扣的代码
这段代码会在商品页价格区域显示用户角色对应的折扣信息,同时展示折扣后的价格:
// 经销商多档折扣 - 商品页显示 add_action( 'woocommerce_single_product_summary', 'display_role_based_discount_on_product_page', 15 ); function display_role_based_discount_on_product_page() { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; if ( ! is_user_logged_in() ) return; // 未登录用户不显示折扣 // 定义角色与折扣率对应关系(和购物车代码保持一致) $role_discounts = array( 'wcwp_reseller_45' => 45, 'wcwp_reseller_40' => 40, 'wcwp_reseller_35' => 35, 'wcwp_reseller_30' => 30, 'wcwp_reseller_25' => 25, 'wcwp_reseller_20' => 20, 'wcwp_reseller_15' => 15, 'wcwp_reseller_10' => 10, ); $user = wp_get_current_user(); $user_discount = 0; // 匹配用户对应的折扣率 foreach ( $role_discounts as $role => $percentage ) { if ( in_array( $role, $user->roles ) ) { $user_discount = $percentage; break; } } if ( $user_discount > 0 ) { global $product; $regular_price = $product->get_regular_price(); $discounted_price = $regular_price * ( 100 - $user_discount ) / 100; // 输出折扣信息 echo '<div class="role-discount-info">'; echo '<p class="discount-label">您的专属折扣:' . $user_discount . '%</p>'; echo '<p class="discounted-price">折扣价:' . wc_price( $discounted_price ) . '</p>'; echo '</div>'; } }
使用说明
- 将上述两段代码添加到你的WooCommerce主题的
functions.php文件中,或者使用代码片段插件添加; - 可以根据需求调整商品页折扣信息的HTML结构和样式,通过CSS自定义显示效果;
- 确保
$role_discounts数组中的角色名称和你实际的用户角色完全一致。
内容的提问来源于stack exchange,提问作者Katan Kid
相关产品推荐
相关产品推荐

