Add an expiration date to WooCommerce orders based on order items count

Viewed 1083

I am trying to set expiration date functionality to my WooCommerce shop.

What I need is an automated system which sets an expiration date to the orders. The expiration date will be 15 days for 1 product, 30 days if you ordered 2, and so on. Basically, expiration_days = order_quantity * 15, and set the date in the order data.

Then, I will need expired orders to be deleted from the orders list in WooCommerce panel.

I have seen similar solutions using hooks, but I don't know how to set the expiration date as metadata. I am stuck here:

add_action( 'woocommerce_checkout_create_order', 'add_expiration' );
function add_expiration( $order ) {

    // Calculate expiration date. 
    // I know how to work with dates, but I haven't found how to get quantity from the order to do the multiply.

    $order->update_meta_data('expiration_date', $expiration_date);
}

Then I will need just a system which checks if current date is less or not than de expiration date. Do not know if I can trigger a check fuction daily using functions.php too, or I need another aproach.

// Daily trigger
function delete_expired( ) {

    // for each order
        // if order.expiration_date > current_date
            // wp_delete_post(order);
}

Hope I explained it well.

1 Answers

You can still get cart items count that will allow to make your calculation and set an expiration date:

add_action( 'woocommerce_checkout_create_order', 'add_expiration' );
function add_expiration( $order, $data ) {
    $items_count  = WC()->cart->get_cart_contents_count();

    $order->update_meta_data('expiration_date', date( 'Y-m-d H:i:s', strtotime( '+'. ( $items_count * 15 ) .' days' ) ) );
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.


Now you can use Action Scheduler plugin, to make a job queue based on that expiration date.

Action Scheduler is a scalable, traceable job queue for background processing…
Note that Action Scheduler library is included / used by WooCommerce and WooCommerce Subscriptions.
The documentation (and examples usage) is on ActionScheduler.org

Action Scheduler is much more easy, efficient and scalable than WordPress Cron.

Note that the rule in StackOverFlow is one question at the time.

Related