With every photo upload, I create a woocommerce product and you might get the idea that at some point I will have lots of unused products. I save product id and image upload links to a text file.

What I am trying to do is to delete a product after 24 hours if it is not in cart and I want to do this with cron.

The problem I have is I do not understand how to make the global woocommerce properties available also for scheduled events (cron).

This is how I set a scheduled event:

add_action('daily_product_removal',  'delete_unused_products' );

function activate() {
    wp_schedule_event( time(), 'daily', 'daily_product_removal' );

function deactivate() {

Woo in cart function:

function woo_in_cart($product_id) {
    global $woocommerce;

    foreach($woocommerce->cart->get_cart() as $key => $val ) {
        $_product = $val['data'];

        if($product_id == $_product->id ) {

       return true;

    return false;

Main function:

function delete_unused_products() {

    $woocommerce = new Client(
            'wp_api' => true,
            'version' => 'wc/v1',

    $myFile = "products.txt";

    $myFileLink = fopen($myFile, 'r');

    $products = [];

     while(!feof($myFileLink)) {
          $this_line = fgets($myFileLink);


     foreach($products as $i => $item) {

        $product = unserialize($item);
        $creation_date_from_file = $product->creation_date;
        $product_id = $product->product_id;

        $createDate = strtotime($creation_date_from_file);

        if (strtotime("$creation_date_from_file +1 day") <= time() && !woo_in_cart($product_id)) { // created more than 24 hours ago and is not added in cart

            $results = $woocommerce->delete('products/' . $product_id, ['force' => true]);

            if (file_exists($item->local_url)) {
        if (file_exists($item->local_mockup_url)) {

        file_put_contents($myFile, str_replace($i . "\r\n", "", file_get_contents($myFile))); // delete the line



The problem I have is that If I run this function under woocommerce specific action hook, lets say:

add_action( 'woocommerce_cart_contents', 'delete_unused_products' );

Its fine, but If I run this as I want (through cron) I get errors, something like $woocommerce->cart is not defined.

Can not wrap my head around how to make this work. Thanks.

1 Answer 1


Not tested, but what if you use


to retrieve the cart contents instead of the global $woocommerce object?

However, I believe the problem is that cart contents require the user's session, and accessing it via cron won't know who the user is. You might need to start querying the database directly through $wpdb in order to find this information outside of a specific user session.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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