Search

How to Delete Products from WooCommerce Shop After Specific Time Period

Listen to this article

delete-products-after-timeWooCommerce users often require a functionality using which products can be made available on the shop page for a specific time duration. After the specific time duration has passed by there should be a functionality to auto delete products. 

When would you need to Delete Products from WooCommerce? 

Such a requirement could arise for a subscription-based multi-vendor site. So, for example, you have a multi-vendor WooCommerce website. Vendors can sell their products from your website by subscribing to various packages that might be available on your site. But what happens after a particular vendor’s subscription expires?? The vendor should now not be able to continue selling any products from your website. For this purpose, there would be a need to either delete products from shop page or save it as a draft to be accessed later from the dashboard.

Steps to Automatically Delete Products from WooCommerce Shop

So, the question still remains is how are we going to delete products from the shop page after a particular time interval. This process would involve the following three steps.

Step 1: Set Time After which a Product should be Deleted

  • The foremost step would be to set a time duration after which system should delete products. This step will be implemented at the time of adding a product to the shop page.
  • The code for this will be written in a function that will be called on the ‘wp_insert_code’ hook. The code to set the time will be as below.
function set_delete_product_meta($id) {
global $wpdb,$current_user;
$posttype = get_post_type($id);
if ( $posttype =='revision' )
   return;
   if($posttype=='product')
   {
        $val=get_post_meta( $id, 'wdm_set_expiry',true);
             if($val!=1)
             {
                $month     = date('m');
                $day      = date('d')+X;
                $year      = date('Y');
                $hour      = date('H');
                $minute  =date('i');        
                $dt = get_gmt_from_date("$year-$month-$day $hour:$minute:0",'U');
                $vars = $id;
                wdm_delete_product($dt,$id,$vars);
                update_post_meta($id,'wdm_set_expiry',1);
             }
    }
    else
    return;
}
add_action('wp_insert_post','set_delete_product_meta');
  • The variable ‘X’ on line 12 should be replaced with the actual duration after which you want the product to be removed from the shop page.

Step 2: Schedule a Cron Job for Product Deletion

  • Now that the time after which product should be deleted from shop page has been set the next step would be to schedule a cron job to actually initiate the deletion process after the set time.
  • In this step it will first be checked if a cron job has been already scheduled for the product. If it has been done then no change will be made to the scheduled time of the existing cron job.
  • In the above code a call has been made to the function ‘wdm_delete_product’ on line 18. It is this function that will actually schedule the cron job and we will need the code below to achieve this functionality.
function wdm_delete_product($remove_date,$id,$vars) {
    if (wp_next_scheduled('wdm_remove_product',array($id)) !== false) 
        wp_clear_scheduled_hook('wdm_remove_product',array($id));
        wp_schedule_single_event($ts,'wdm_remove_product',array($id));
        // Update Post Meta
        update_post_meta($id, 'wdm_product_remove_date', $remove_date);
        update_post_meta($id, 'wdm_product_remove_date-value', $vars);
}

Ensure that the Cron Job Runs as Expected

  • As you might already know, the wp-cron.php triggers crons on your WordPress website. But this file does not always execute as expected. It only executes when someone visits your site. And this could be a problem.
  • Due to the inefficiency of the WP cron, it may happen that the cron you’ve set to delete a product might not get executed as expected.
  • So, to ensure that the cron gets executed, you could use a service like EasyCron
  • The EasyCron service ensures that the wp-cron.php executes on a timely basis, thus it will ensure that the ‘wdm_delete_product’ function is called, and the products scheduled to be removed from the store, are deleted.

[space]

Step 3: Delete Products after Set Time has Passed By

  • Now that the deletion process has been initiated it would require us to add a function which will delete products from the shop page after the deletion process has been initiated.
  • As you can see in the code above a function ‘wdm_remove_product’ has been called. This function will carry out the deletion of products from the shop page and will be called on the ‘wdm_remove_product’ hook that has been defined in the ‘wdm_delete_product’ function defined in step two.
function wdm_remove_product($id){
         global $wpdb;
         if (empty($id)){ 
            return false;
         }
         if (is_null(get_post($id))){
            return false;
         }
         $pr_value = get_post_meta($id,'wdm_product_remove_date-value',true);
         // wp_delete_post($pr_value) ; //This will delete product
         $wpdb->query("Update $wpdb->posts set post_status='draft' where ID='$id'");// Change status to draft
}
add_action('wdm_remove_product','wdm_remove_product');
All the above code needs to be added to the functions.php file of your theme. Alternatively, you can create a separate plugin folder and add this code to a php file in this folder. My suggestion to you would be to use the second approach as any customizations done in the theme files will be lost in case the theme is updated. And with that you would have successfully implemented the functionality to automatically delete products on your WooCommerce website.
[space]
That’s all from my end. I hope you found this post helpful. You can use the comments section for any queries that you may have. I’ll back to you with answers ASAP! Until then Adios!
Aparna Gawade

Aparna Gawade

10 Responses

  1. Hi Aparna G,

    I have read your article about “How to Delete Products from WooCommerce Shop After Specific Time Period”, it is really nice! 🙂

    What I need is this to be done only for the sold-out products.

    Could you please help me?

    1. Hi Nikos,

      It’s simple. You’ll have to call the wdm_remove_product function on the woocommerce_no_stock hook. The product will be passed as a parameter to the function. To delete the product you have to fire a delete query instead of update query. 🙂

  2. How could I update this to mark a product in WooCommerce as “draft” state after 7 days if it has an out of stock meta? I tried this below but its not working:

    function set_delete_product_meta($id) {
    global $wpdb,$current_user,$post;
    $cfstockstatus = get_post_meta($post->ID, ‘_stock_status’, true);
    if ( $cfstockstatus == instock )
    return;
    if( $cfstockstatus == outofstock )
    {
    $val=get_post_meta($post->ID, ‘wdm_set_expiry’,true);
    if($val!=1)
    {
    $month = date(‘m’);
    $day = date(‘d’)+7;
    $year = date(‘Y’);
    $hour = date(‘H’);
    $minute =date(‘i’);
    $dt = get_gmt_from_date(“$year-$month-$day $hour:$minute:0”,’U’);
    $vars = $id;
    wdm_delete_product($dt,$id,$vars);
    update_post_meta($id,’wdm_set_expiry’,1);
    }
    }
    else
    return;
    }
    add_action(‘woocommerce_single_product_summary’,’set_delete_product_meta’);

    Any help/ideas would be greatly appreciated.

  3. Hello Aparna

    I did compile all the functions into one php and try to test it on one of my demo site. I set it as one day duration but no luck after the end. No products are deleted from the products area. I also checked the cron task using a plugin named “Core Control”. It shows all the cron task which are in action. But I didn’t found your corn task which also suppose to there.

    Did I miss anything?

  4. Hello
    i was looking if someone can help me with a code for function or a plugin that will HIDE a product of a vendor who canceled his subscription. So basically, i applied a to a membership that will allow me to be a vendor but once i became a vendor and posted a product it shows in the product page but once i cancel my subscription it still shows the product. Now, how do i hide that product from the product page so no one could see or buy it and once the vendor resubscribe it will show again on the product page. Please help me with this. i been looking for a solution and haven’t find any.

    Thanks a lot.

  5. there is an error in step2 script:
    wp_schedule_single_event($ts,’wdm_remove_product’,array($id)); should be wp_schedule_single_event($remove_date,’wdm_remove_product’,array($id));

    also this script won’t if there are more than 30~40 products to remove per one run. it just outrun maximum execution time wich on most shared hostings sets to 30 seconds

  6. Hi! can this be done on products below a price?

    for example… I want to delete everithing that´s below $100

    Just one time, doesn´t need to be a cron job or an automated task,

Leave a Reply

Your email address will not be published. Required fields are marked *

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

WordPress Development

Custom WordPress Solutions, for You

LearnDash Development

Custom LearnDash Solutions, for You

WooCommerce Development

Custom WooCommerce Solutions, for You

WordPress Plugins

Scale your WordPress Business

WooCommerce Plugins

Scale your WooCommerce Business

LearnDash Plugins

Scale your LearnDash Business

Label

Title

Subtext

Label

Title

Subtext

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads