Woocommerce: Possible to add free gift for nth order?

289 Views Asked by At

I've been wondering this for some time but have so far drawn a blank...

Does anybody know whether it is possible to add a free gift to an arbitrary Woocommerce product order automatically upon completion? Either site-wide or with differing values per product?

I.E.
Product added to cart is the 100th order of said item
Order is paid/ completes
User is either redirected to free gift page or pop up or receives email (whichever is most practical)

:-) Hope this seems relevant - any pointers much appreciated!

Ed

EDIT: So, after some help from Aki (below) and online searching, I've come up with this, but still can't get it to work...what am I missing?

add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);

function custom_process_order($order_id) {

 //First We are chceking order is paid or not with the order metafields
 $transactionId = get_post_meta($order_id,'_transaction_id', true );
 if(isset($transactionId))
 {
    //getting the count of order
    $orderCount = get_option('orderCount');
    if($orderCount == 99)
    {
        //let's reset order count option zero
        $orderCount = 0;

        //send email or redirect code or popup code
$message = "You're the 100th order of this item, so please, have one on us..Free gift!";
echo "<script type='text/javascript'>alert('$message');</script>";
    }else
    {
        $orderCount = (int) $orderCount+1;
    }
    update_option( 'orderCount', $orderCount );
 }
}
1

There are 1 best solutions below

4
On

For this you need to do some code directly it is fleasible you need to set the count than you can reach to your goal.

you need to set the order count in with help of update_option function than you can do anything.

add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);

function custom_process_order($order_id) {

 //First We are chceking order is paid or not with the order metafields
 $transactionId = get_post_meta($order_id,'_transaction_id', true );
 if(isset($transactionId))
 {
    //getting the count of order
    $orderCount = get_option('orderCount');
    if($orderCount == 99)
    {
        //let's reset order count option zero
        $orderCount = 0;

        //send email or redirect code or popup code

    }else
    {
        $orderCount = (int) $orderCount+1;
    }
    update_option( 'orderCount', $orderCount );
 }
}