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

WooCommerce中禁止Dokan卖家购自身商品,修复隐藏加购按钮无效问题

修复Dokan卖家自购限制与支付方式未配置隐藏加购按钮的问题

原代码存在的问题

  • 钩子注册错误:add_filter里同时写了两个钩子标识,还缺失自定义回调函数名
  • 参数匹配错误:woocommerce_is_purchasable钩子默认只有2个参数,原代码声明了3个参数但钩子的参数数量设置为2,导致第三个参数无法正确传递
  • 支付方式获取逻辑错误:错误尝试用函数调用形式获取支付网关,Dokan中需用dokan_get_seller_payment_methods()获取卖家支付方式
  • 缺失核心需求逻辑:完全没实现禁止卖家购买自身店铺商品的功能

修正后的完整代码

add_filter( 'woocommerce_is_purchasable', 'restrict_seller_self_purchase_and_hide_cart_for_no_payment', 10, 2 );

function restrict_seller_self_purchase_and_hide_cart_for_no_payment( $purchasable, $product ) {
    // 获取商品所属的卖家ID
    $seller_id = get_post_field( 'post_author', $product->get_id() );
    // 当前登录用户的ID
    $current_user_id = get_current_user_id();

    // 禁止卖家购买自己店铺的商品
    if ( $current_user_id === $seller_id && dokan_is_seller( $current_user_id ) ) {
        return false;
    }

    // 检查卖家是否配置了支付方式
    $seller_payment_methods = dokan_get_seller_payment_methods( $seller_id );
    // 没有可用支付方式的话,隐藏加入购物车按钮
    if ( empty( $seller_payment_methods ) ) {
        return false;
    }

    // 满足所有条件则允许购买
    return $purchasable;
}

代码说明

  • 钩子注册:正确绑定woocommerce_is_purchasable钩子,自定义回调函数名,参数数量设置为2(对应钩子的两个原生参数:是否可购买、商品对象)
  • 自购限制逻辑:对比当前登录用户ID和商品卖家ID,同时验证当前用户是Dokan卖家,返回false直接禁止购买
  • 支付方式检查:用Dokan内置函数dokan_get_seller_payment_methods()获取卖家已配置的支付方式,若为空则返回false隐藏加购按钮
  • 最终返回:只有当用户不是卖家本人,且卖家已配置好支付方式时,才保留原本的可购买状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:47:36