Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save helgatheviking/7730224e3189516dc7e03474ef752d9f to your computer and use it in GitHub Desktop.
Save helgatheviking/7730224e3189516dc7e03474ef752d9f to your computer and use it in GitHub Desktop.
Schedule a task to run daily to delete WooCommerce persistent carts
<?php
/**
* Plugin Name: Clear persistent carts daily
* Plugin URI: https://gist.github.com/
* Description: Schedule a task to run daily to delete WooCommerce persistent carts
* Version: 1.0.0
* Author: Kathy Darling
* Author URI: http://kathyisawesome.com/
* WC requires at least: 6.3.0
* WC tested up to: 6.3.0
* Requires at least: 5.9.0
*
* Copyright: © 2022
* License: GNU General Public License v3.0
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
function kia_install_clear_cart_action() {
if ( ! function_exists( 'WC') ) {
return;
}
$next_scheduled_date = WC()->queue()->get_next( 'kia_run_batch_user_cart_update', null, 'kia-persistent-cart-updates' );
if ( ! $next_scheduled_date && false === get_transient( 'kia_clear_persistent_carts_scheduled' ) ) {
WC()->queue()->schedule_cron(
'15 1 * * *', // Daily at 1:15am (I hope)
'kia_run_batch_user_cart_update',
array(
'step' => 1,
),
'kia-persistent-cart-updates'
);
set_transient( 'kia_clear_persistent_carts_scheduled', 'yes' );
}
}
add_action( 'admin_init', 'kia_install_clear_cart_action' );
/**
* Batch process all user meta
*
* @param int $step - count of interations
*/
function kia_batch_clear_persitent_carts( $step = 1 ) {
if ( apply_filters( 'woocommerce_persistent_cart_enabled', true ) ) {
$batch_size = 20;
$step = $step ? intval( $step ) : 1;
$offset = $batch_size * ( $step - 1 );
$user_query = new WP_User_Query( array(
'number' => $batch_size,
'offset' => $offset
'fields' => 'ID',
);
if ( $user_query ) {
$get_current_blog_id = get_current_blog_id();
foreach( $user_query as $user_id ) {
delete_user_meta( $user_id, '_woocommerce_persistent_cart_' . $get_current_blog_id ); // This might be more efficient as an SQL query (no do_action()).
}
$step++;
// Schedule the next batch.
WC()->queue()->schedule_single(
time(),
'kia_run_batch_user_cart_update',
array(
'step'=> $step,
),
'kia-group'
);
}
}
}
add_action( 'kia_run_batch_user_cart_update', 'kia_batch_clear_persitent_carts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment