0

I have created custom coupons per logged in customers and set their initial amount to 0. After that by continuing customers to buy more they get i.e 10$ coupon amount increase that can be used in their next purchases. this way every custom coupon that belongs to that customer should be updated in every usage. In order to make them special per customer, I used customer email and also woocommerce_coupon_is_valid hook as follow:

add_filter( 'woocommerce_coupon_is_valid', 'coupon_is_valid', 10, 2);

function coupon_is_valid($result, $coupon){

    $restricted_emails = $coupon->get_email_restrictions();

    return ( in_array( wp_get_current_user()->user_email, $restricted_emails ) ? $result : false );
}

My problem here is that after applying coupon by customer its amount is not updated ( It should be decreased ). Is there any special woocommerce hook to update coupon after checkout?

Thanks in advance.

0

You could use the hook woocommerce_applied_coupon, example:

add_action( 'woocommerce_applied_coupon', 'increase_applied_coupon_amount' );
function increase_applied_coupon_amount($coupon_code) {
    // Programmatically adjust the coupon here
}
  • Thank you so much for your response. Actually I had already used this hook and it doesn't fulfill my needs. I need to access coupon data and discount amount in order after checkout. Fortunately I could find a solution that share it in the next post. – Kourosh May 10 at 8:42
0

First of all thanks to @LoicTheAztec answer to this question. I used woocommerce_thankyou hook as follows:

add_action('woocommerce_thankyou', 'apply_coupon_discount', 10, 1);

function apply_coupon_discount($order_id){

    global $wpdb;

    $coupon_amount = 0;

    $order = wc_get_order($order_id);
    $discount_amount = $order->get_discount_total();

    $table = $wpdb->prefix . "woocommerce_order_items";
    $order_items = $wpdb->get_results( "SELECT  *  FROM  $table  WHERE  order_id = $order_id ");

    foreach ($order_items as $item_values){

        if($item_values->order_item_type == 'coupon'){

            // Retrieving the coupon ID reference
            $coupon_post_obj = get_page_by_title( $item_values->order_item_name, OBJECT, 'shop_coupon' );
            $coupon_id = $coupon_post_obj->ID;

            // Get an instance of WC_Coupon object (necesary to use WC_Coupon methods)
            $coupons_obj = new WC_Coupon($coupon_id);

            $coupon_amount = $coupons_obj->get_amount();
        }
    }

    if($discount_amount > 0){ // coupon has been applied

        update_post_meta($coupon_id, 'coupon_amount', $coupon_amount - $discount_amount);
    }

}

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.