2

I want to add an item to the cart (that same item gets discounted with the coupon) upon using a coupon code (with a hook).

E.g. when using the coupon code SAMPLECODE, a product is added to the cart with a $2 discount. The coupon is set up to apply a $2 discount for that product only.

The problem is, that my coupon code only applies to the item that is going to be added programmatically, so it fails the eligibility check and doesn't get to woocommerce_applied_coupon.

So is there a hook that fires before checking if the coupon is valid?

Or should I just do it via javascript when applying a coupon? Is there a way to do it via AJAX?

0

Its the woocommerce_get_shop_coupon_data filter, example code:

add_filter ( 'woocommerce_get_shop_coupon_data', 'mp_create_coupon', 10, 2  );
 
function mp_create_coupon( $data, $code ) {
    // Check if the coupon has already been created in the database
    global $wpdb;
    $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'              => 'fixed_cart',
            'coupon_amount'              => 100, // value
            'individual_use'             => 'no',
            'product_ids'                => array(),
            'exclude_product_ids'        => array(),
            'usage_limit'                => '',
            'usage_limit_per_user'       => '1',
            'limit_usage_to_x_items'     => '',
            'usage_count'                => '',
            'expiry_date'                => '2018-09-01', // YYYY-MM-DD
            'free_shipping'              => 'no',
            'product_categories'         => array(),
            'exclude_product_categories' => array(),
            'exclude_sale_items'         => 'no',
            '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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.