使用电子邮件地址作为Woocommerce优惠券代码

时间:2017-07-28 19:50:41

标签: php wordpress woocommerce

我正在尝试创建一个使用电子邮件地址作为woocommerce优惠券代码的功能。我的代码之前完美无缺,但突然间它停止了工作。我使用此woocommerce_get_shop_coupon_data过滤器来获取优惠券数据。请帮帮我。

<?php 
add_filter ( 'woocommerce_get_shop_coupon_data', 'firefog_create_coupon', 10, 2  );

function firefog_create_coupon($data, $code) {
    global $wpdb;

    //getting the coupon input value 
    $coupon_code = $_POST['coupon_code'] ;

    //check user input is like email
        if (filter_var($coupon_code, FILTER_VALIDATE_EMAIL)) {  
            $code = $coupon_code ;
        }

    // Check if the coupon has already been created in the database
    $sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'shop_coupon' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1;", $code );
    $coupon_id = $wpdb->get_var( $sql );

    if ( empty( $coupon_id ) ) {
        // Create a coupon with the properties you need
        $data = array(
            'discount_type'              => 'percent',
            'coupon_amount'              => 15, // value
            'individual_use'             => 'false',
            'product_ids'                => array(),
            'exclude_product_ids'        => array(),
            'usage_limit'                => '',
            'usage_limit_per_user'       => '',//Limit
            'limit_usage_to_x_items'     => '',
            'usage_count'                => '',
            'expiry_date'                => '2020-12-31', // YYYY-MM-DD
            'free_shipping'              => 'false',
            'product_categories'         => array(),
            'exclude_product_categories' => array(),
            'exclude_sale_items'         => 'false',
            'minimum_amount'             => '',
            'maximum_amount'             => '',
            'customer_email'             => array()
        );
        // Save the coupon in the database
        $coupon = array(
            'post_title' => $code,
            'post_content' => '',
            'post_status' => 'publish',
            'post_author' => 1,
            'post_type' => 'shop_coupon'
        );
        $new_coupon_id = wp_insert_post( $coupon );
        // Write the $data values into postmeta table
        foreach ($data as $key => $value) {
            update_post_meta( $new_coupon_id, $key, $value );
        }
        return $data;
    }
}

0 个答案:

没有答案