Search code examples
wordpresswoocommercehook-woocommerce

Find coupon creator on payment completion in WooCommerce


I'm developing a plugin.

I need to find out when any coupon issued by a specific user_id used in any order on payment completion.


Solution

  • It is possible to retrieve coupons used by an order using get_coupons() method on WC_Order instance:

    $coupons = $order->get_coupons();
    

    If you need only coupon codes just call get_coupon_codes(). It returns an array of strings:

    $coupon_codes = $order->get_coupon_codes();
    

    Now if you want to check it on order payment you WooCommerce hooks:

    add_action( 'woocommerce_payment_complete', 'my_payment_completion_hook' );
    
    function aac_wc_payment_complete_hook( $order_id ) {
        $order        = wc_get_order( $order_id );
        $used_coupons = $order->get_coupon_codes();
        if ( count( $used_coupons ) ) {
            $coupon       = new WC_coupon( $used_coupons[0] );
            $post         = get_post( $coupon->id );
            $user_id = $post->post_author;
            if ( $user_id == 100) {
                // Do some stuff
            }
        }
    }