如何在WooCommerce中根据用户累计消费额展示对应等级提示文本
WooCommerce 按累计消费实现Tier会员等级提示解决方案
将以下代码添加到站点子主题的functions.php文件,或通过Code Snippets这类代码管理插件添加即可实现需求:
// 获取用户累计消费并返回对应等级提示 function get_user_tier_notice() { // 仅对已登录用户生效 if (!is_user_logged_in()) return ''; $user_id = get_current_user_id(); // 获取用户累计总消费(仅统计已完成订单,自动排除退款金额) $total_spent = wc_get_customer_total_spent($user_id); // 自定义Tier等级规则,可按需修改阈值、等级名、提示语 $tier_rules = [ [ 'threshold' => 600, 'tier_name' => 'Tier 1', 'notice' => '恭喜您已成为Tier 1等级会员' ], [ 'threshold' => 1200, 'tier_name' => 'Tier 2', 'notice' => '恭喜您已成为Tier 2等级会员' ], [ 'threshold' => 2000, 'tier_name' => 'Tier 3', 'notice' => '恭喜您已成为Tier 3等级会员' ], [ 'threshold' => 3000, 'tier_name' => 'Tier 4', 'notice' => '恭喜您已成为Tier 4等级会员' ] ]; // 按阈值从高到低排序,匹配用户当前可获得的最高等级 usort($tier_rules, function($a, $b) { return $b['threshold'] - $a['threshold']; }); foreach ($tier_rules as $tier) { if ($total_spent >= $tier['threshold']) { return '<div class="woocommerce-info tier-notice">' . $tier['notice'] . '</div>'; } } // 未达到最低等级时可自定义提示,不需要则保留返回空即可 // return '<div class="woocommerce-notice">当前累计消费还差'. (600 - $total_spent) .'美元即可升级为Tier 1会员</div>'; return ''; } // 方案1:自动在「我的账户」页面顶部显示等级提示 add_action('woocommerce_before_my_account', 'display_user_tier_notice'); function display_user_tier_notice() { echo get_user_tier_notice(); } // 方案2:生成短码,可插入任意页面、文章、侧边栏小工具中显示 add_shortcode('show_user_tier_badge', 'get_user_tier_notice');
自定义调整说明
- 可直接修改
$tier_rules数组内的配置参数,threshold为等级要求的最低累计消费金额(单位和站点货币单位一致),notice为对应等级展示的提示文本 - 提示框的样式可通过自定义
.tier-notice的CSS规则调整,匹配站点整体风格 - 若需要在其他固定位置显示,可更换
add_action的钩子参数,比如换成woocommerce_before_main_content即可在全站主内容顶部显示
验证方法
可在WooCommerce后台用户编辑页,手动修改指定用户的「累计消费」字段数值,刷新前端页面对应位置即可验证显示效果。
内容的提问来源于stack exchange,提问作者Nath
相关产品推荐
相关产品推荐

