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

Gravity Forms提交后自动生成WooCommerce唯一优惠券问题求助

问题修复说明

你代码存在4个直接导致优惠券创建失败的问题,修复后即可正常生成WooCommerce优惠券,同时补充了发邮件的逻辑满足你的业务需求:

  • 全代码存在中文弯引号语法错误,PHP无法识别,全部替换为英文单引号
  • 传入的元数据是EDD插件的字段,和WooCommerce要求的优惠券字段不匹配,已调整字段对应关系
  • 优惠券过期日期格式错误,WooCommerce要求传入Unix时间戳,已修正格式
  • 唯一性校验仅检查了Gravity Forms的提交记录,未校验WooCommerce已有优惠券,已补充校验逻辑
  • 补充了用户提交表单后发送优惠券邮件的逻辑,匹配你「提交后发有效期2周专属优惠券」的需求

修正后完整可运行代码

// 定义配置常量
define( 'ENGWP_FORM_ID', 276 ); // Gravity Forms表单ID
define( 'ENGWP_EMAIL_FIELD_ID', 1 ); // 表单中邮箱字段的ID,根据你实际的字段ID修改
define( 'ENGWP_SOURCE_FIELD_ID', 2 ); // 表单中存储优惠码的字段ID
define( 'ENGWP_CODE_LENGTH', 12 ); // 优惠码长度
define( 'ENGWP_CODE_CHARS', '1234567890QWERTYUIOPASDFGHJKLZXCVBNM' ); // 优惠码可用字符
define( 'ENGWP_CODE_PREFIX', '17-' ); // 优惠码前缀
define( 'ENGWP_DISCOUNT_TYPE', 'percent' ); // 折扣类型:percent为百分比,fixed_cart为固定金额
define( 'ENGWP_DISCOUNT_AMOUNT', 10 ); // 折扣数值
define( 'ENGWP_MAX_USES', 1 ); // 优惠券最大使用次数
define( 'ENGWP_MIN_PRICE', 0 ); // 最低消费金额
define( 'ENGWP_PRODUCT_REQS', '' ); // 适用商品ID,多个用英文逗号分隔
define( 'ENGWP_REQS_CONDITION', 'any' ); // 适用商品规则:any为包含任意指定商品即可用,all为全部包含才可用
define( 'ENGWP_EXCLUDE_PRODUCTS', '' ); // 排除商品ID,多个用英文逗号分隔

// 优惠券有效期:当前时间+14天的Unix时间戳
$exp_date = strtotime( "+14 days" );

class GW_Create_Coupon {
    public function __construct( $args = array() ) {
        $this->_args = wp_parse_args( $args, array(
            'form_id'         => false,
            'source_field_id' => false,
            'email_field_id'  => false,
            'plugin'          => 'wc',
            'amount'          => 0,
            'type'            => '',
            'meta'            => array()
        ) );
        add_action( 'init', array( $this, 'init' ) );
    }

    public function init() {
        if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.8', '>=' ) ) {
            return;
        }
        add_action( 'gform_after_submission', array( $this, 'create_coupon' ), 10, 2 );
    }

    public function create_coupon( $entry, $form ) {
        if( ! $this->is_applicable_form( $form ) ) {
            return;
        }
        $coupon_code = rgar( $entry, $this->_args['source_field_id'] );
        $customer_email = rgar( $entry, $this->_args['email_field_id'] );
        $amount = $this->_args['amount'];
        $type = $this->_args['type'];

        $plugin_func = array( $this, sprintf( 'create_coupon_%s', $this->_args['plugin'] ) );
        if( is_callable( $plugin_func ) ) {
            $coupon_id = call_user_func( $plugin_func, $coupon_code, $amount, $type, $customer_email );
            if($coupon_id) {
                // 发送优惠券邮件
                $this->send_coupon_email($customer_email, $coupon_code);
            }
        }
    }

    public function create_coupon_wc( $coupon_code, $amount, $type, $customer_email ) {
        // 检查WooCommerce中是否已存在相同优惠码
        if( wc_get_coupon_id_by_code($coupon_code) ) {
            return false;
        }
        $coupon = array(
            'post_title' => $coupon_code,
            'post_content' => '',
            'post_status' => 'publish',
            'post_author' => 1,
            'post_type' => 'shop_coupon'
        );
        $new_coupon_id = wp_insert_post( $coupon );
        if(is_wp_error($new_coupon_id)) {
            return false;
        }
        // 合并WooCommerce优惠券元数据
        $meta = wp_parse_args( $this->_args['meta'], array(
            'discount_type' => $type,
            'coupon_amount' => $amount,
            'individual_use' => 'yes',
            'product_ids' => ENGWP_PRODUCT_REQS,
            'exclude_product_ids' => ENGWP_EXCLUDE_PRODUCTS,
            'usage_limit' => ENGWP_MAX_USES,
            'expiry_date' => $this->_args['meta']['expiration'],
            'apply_before_tax' => 'no',
            'free_shipping' => 'no',
            'exclude_sale_items' => 'no',
            'minimum_amount' => ENGWP_MIN_PRICE,
            'customer_email' => array($customer_email)
        ) );
        foreach( $meta as $meta_key => $meta_value ) {
            update_post_meta( $new_coupon_id, $meta_key, $meta_value );
        }
        return $new_coupon_id;
    }

    public function send_coupon_email($email, $coupon_code) {
        $subject = '你的专属优惠码已到账';
        $message = '您好,感谢您的提交!您的专属优惠码是:'.$coupon_code.',有效期14天,全场通用满减可用。';
        wp_mail( $email, $subject, $message );
    }

    function is_applicable_form( $form ) {
        $form_id = isset( $form['id'] ) ? $form['id'] : $form;
        return $form_id == $this->_args['form_id'];
    }
}

// 实例化优惠券生成类
new GW_Create_Coupon( array(
    'form_id'         => ENGWP_FORM_ID,
    'source_field_id' => ENGWP_SOURCE_FIELD_ID,
    'email_field_id'  => ENGWP_EMAIL_FIELD_ID,
    'amount'          => ENGWP_DISCOUNT_AMOUNT,
    'type'            => ENGWP_DISCOUNT_TYPE,
    'meta'            => array(
        'expiration' => $exp_date
    )
) );

// 生成唯一优惠码
add_filter( 'gform_field_value_uuid', 'gw_generate_unique_code' );
function gw_generate_unique_code() {
    $length = ENGWP_CODE_LENGTH;
    $chars = ENGWP_CODE_CHARS;
    $prefix = ENGWP_CODE_PREFIX;
    $unique = '';
    $chars_length = strlen( $chars )-1;
    for( $i = 0 ; $i < $length ; $i++ ) {
        $unique .= $chars[ rand( 0, $chars_length ) ];
    }
    do {
        $unique = $prefix . str_shuffle( $unique );
    } while ( !gw_check_unique_code( $unique ) );
    return $unique;
}

// 校验优惠码唯一性
function gw_check_unique_code( $unique ) {
    global $wpdb;
    // 检查Gravity Forms提交记录
    $table = $wpdb->prefix . 'rg_lead_detail';
    $form_id = ENGWP_FORM_ID;
    $field_id = ENGWP_SOURCE_FIELD_ID;
    $result = $wpdb->get_var( $wpdb->prepare("SELECT value FROM $table WHERE form_id = %d AND field_number = %d AND value = %s", $form_id, $field_id, $unique) );
    // 检查WooCommerce已有优惠券
    if( wc_get_coupon_id_by_code($unique) ) {
        $result = $unique;
    }
    return empty( $result );
}

使用注意事项

  • 请先修改代码开头的ENGWP_EMAIL_FIELD_ID常量值为你Gravity Forms表单中邮箱字段的实际ID
  • 优惠码邮件内容可根据你的需求修改send_coupon_email方法里的标题和正文
  • 测试时请先确认你的WordPress站点wp_mail函数可正常发送邮件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:45:04