You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

仅在WooCommerce前端为登录用户设置3%折扣的问题

WooCommerce登录用户3%折扣:排除后台生效的正确实现

我需要为WooCommerce商店的所有登录用户(包括前台的管理员账号)添加3%的购物折扣,最初实现的代码如下:

<?php
add_filter( 'woocommerce_product_get_price', 'products_custom_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_price', 'products_custom_price', 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'products_custom_price', 10, 2 );
// add_filter( 'woocommerce_product_get_sale_price', 'products_custom_price', 10, 2 );
function products_custom_price( $price, $product ){
    if (!is_user_logged_in())
        return $price;
    
    $discount = $price * 0.03;
    
    return $price - $discount;
}

这段代码能实现前台的折扣功能,但存在问题:它会在WordPress后台生效,导致管理员在后台创建或编辑商品时,看到和编辑的都是折扣后的价格,完全不符合后台管理的需求。

我曾尝试修改判断条件,通过检测管理员权限来跳过折扣:

if (!is_user_logged_in() || current_user_can( 'manage_options' ) )

但这不是理想方案——这样设置后,管理员在前台也看不到折扣价,违背了“管理员前台同样享受折扣”的需求。

正确解决方案:判断当前是否处于后台环境

核心思路是使用WordPress的is_admin()函数,直接判断当前是否在后台操作,后台则直接返回原价,前台登录用户(包括管理员)才应用折扣逻辑。修改后的完整代码如下:

<?php
add_filter( 'woocommerce_product_get_price', 'products_custom_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_price', 'products_custom_price', 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'products_custom_price', 10, 2 );
// add_filter( 'woocommerce_product_get_sale_price', 'products_custom_price', 10, 2 );
function products_custom_price( $price, $product ){
    // 后台直接返回原价,不应用折扣
    if (is_admin()) {
        return $price;
    }
    
    // 未登录用户返回原价,登录用户应用3%折扣
    if (!is_user_logged_in()) {
        return $price;
    }
    
    $discount = $price * 0.03;
    return $price - $discount;
}

代码说明

  • is_admin():准确判断当前是否处于WordPress后台(包括商品编辑、管理页面),后台模式下直接返回商品原价,避免影响管理员的商品设置操作。
  • 保留is_user_logged_in()判断:确保只有登录用户(包括前台浏览的管理员账号)才能享受3%折扣,未登录用户看到的是原价。

这样既解决了后台折扣生效的问题,又保证了管理员在前台能正常享受折扣,完全符合需求。

内容的提问来源于stack exchange,提问作者lemek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 15:31:17