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:
$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
}
}
My problem is If I run this function under woocommerce specific action hook, lets say:
add_action( 'woocommerce_cart_contents', 'delete_unused_products' );
I run this as I want (through cron) I get errors, something like $woocommerce->cart is not defined. Kindly remove my issue.