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() {
wp_clear_scheduled_hook('daily_product_removal');
}
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(
'site_link',
'ck_numbers',
'cs_numbers',
[
'wp_api' => true,
'version' => 'wc/v1',
]
);
$myFile = "products.txt";
$myFileLink = fopen($myFile, 'r');
$products = [];
while(!feof($myFileLink)) {
$this_line = fgets($myFileLink);
array_push($products,$this_line);
}
fclose($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)) {
unlink($item->local_url);
}
if (file_exists($item->local_mockup_url)) {
unlink($item->local_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.