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

如何为AffiliateWP优惠券限制PHP代码添加指定IF语句例外

解决方案:允许Affiliate使用特定前缀的自分配优惠券

原代码用于阻止Affiliate使用自身被分配的WooCommerce优惠券,现需添加例外规则:当优惠券代码以affiliate-credit开头时,允许该Affiliate使用此优惠券。以下是修改后的完整代码:

<?php
/**
 * Plugin Name: AffiliateWP - Block WooCommerce Assigned Affiliate Coupon If Affiliate Purchasing
 * Plugin URI: http://affiliatewp.com
 * Description: Prevents assigned affiliate coupon codes from being used on the WooCommerce order if the affiliate is the purchaser, except for affiliate-credit prefix coupons
 * Author: AffiliateWP
 * Author URI: https://affiliatewp.com
 * Version: 1.1
 */
/**
 * Make assigned coupon invalid if customer is an affiliate, except for affiliate-credit prefix coupons.
 */
function affwp_custom_block_affiliate_coupon_if_customer_affiliate( $condition, $coupon, $vars ) {
    
    if ( ! function_exists( 'affiliate_wp' ) ) {
        return $condition; // 确保AffiliateWP已安装,否则直接返回原状态
    }
    $current_user_id = get_current_user_id();
    
    if ( empty( $current_user_id ) ) {
        return $condition; // 用户未登录,直接返回原状态
    }
    if ( ! affwp_is_affiliate( $current_user_id ) ) {
        return $condition; // 当前用户不是Affiliate,直接返回原状态    
    }

    // 先检查优惠券是否以affiliate-credit开头,符合则直接允许使用
    $coupon_code = is_object($coupon) ? $coupon->code : $coupon;
    // 兼容PHP 7.x及以下版本用substr,PHP 8+可直接用str_starts_with
    if ( substr( $coupon_code, 0, 17 ) === 'affiliate-credit' ) {
        // if ( str_starts_with( $coupon_code, 'affiliate-credit' ) ) { // PHP 8+ 写法
        return true;
    }
    
    if ( empty( $coupon->id ) ) {
        $coupon = affwp_get_coupon( $coupon_code );
        
        if ( false !== $coupon && affwp_get_affiliate_user_id( $coupon->affiliate_id ) === $current_user_id ) {
            return false; // 该动态优惠券属于当前Affiliate,禁止使用
        }
    }
    $is_tracked_coupon = get_post_meta( $coupon->id, 'affwp_discount_affiliate', true );
    if ( affwp_get_affiliate_user_id( $is_tracked_coupon ) === $current_user_id ) {
        return false; // 该优惠券属于当前Affiliate,禁止使用
    }
    return $condition;
}
add_filter( 'woocommerce_coupon_is_valid', 'affwp_custom_block_affiliate_coupon_if_customer_affiliate', 10, 3 );

修改说明

  1. 提前添加例外判断:在所有阻止逻辑之前,先检查优惠券代码是否以affiliate-credit开头,符合条件则直接返回true,跳过后续阻止逻辑。
  2. 兼容不同PHP版本:
    • PHP 8.0及以上版本可使用更简洁的str_starts_with( $coupon_code, 'affiliate-credit' )写法。
    • 低版本PHP通过substr截取前17个字符(与affiliate-credit长度匹配)进行判断。
  3. 代码健壮性优化:先统一获取优惠券代码,确保无论传入的是对象还是字符串都能正确取值。
  4. 插件信息更新:修改插件描述说明新增的例外规则,同步更新版本号为1.1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:25:04