Delete woocommerce customer sessions and transients automatically

One of my client’s site was slowed down too much and its waiting time was 6 to 7 seconds. I found the root cause which was because the wp_options table was filled with a lot of customer sessions data that increased table size to 1.7 GB. It took 6-7 hours to delete 2 million rows. I know I can now delete sessions and transients manually by going to Woocomerce > System Status > Tools > Clear all sessions & Clear transients but I want it to be done automatically after one or two days. Is there anything could be done like creating cron job etc?
Thanks

Related posts

2 comments

  1. long time later but that awnser will can help someone

    below the code will execute every day (from your current time), the clean session/cart Woocommerce.

    // clean cart every day
    if (!wp_next_scheduled('cron_wc_clean_cart')) {
        wp_schedule_event( time(), 'daily', 'cron_wc_clean_cart' );
    }
    
    add_action ( 'cron_wc_clean_cart', 'wc_clean_session_cart' );
    function wc_clean_session_cart() {
        global  $wpdb;
    
        $wpdb->query( "TRUNCATE {$wpdb->prefix}woocommerce_sessions" );
        $wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key='_woocommerce_persistent_cart_" . get_current_blog_id() . "';" );
        wp_cache_flush();
    }
    

    for transients, its that function in wc:

    wc_delete_expired_transients()
    

Comments are closed.