I have a recurring order weekly button on my WooCommerce, when activated, it clones the exact order weekly.
function cron_add_weekly( $schedules ) {
$schedules['everyweek'] = array(
'interval' => 60 * 60 * 24 * 7, # 60 * 60 * 24 * 7 = 604,800, seconds in a week
'display' => __( 'Once Every Week' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'cron_add_weekly' );
add_action('woocommerce_order_action_clone_order_weekly', 'cronstarter_activation_weekly');
function cronstarter_activation_weekly( $order ) {
if ( ! is_a($order, 'WC_Order') ) {
return;
}
$order_number = $order->get_order_number();
$name = $order->get_billing_company();
// Pass order number and name as arguments
$args = array( $order, $order_number, $name );
if( ! wp_next_scheduled( 'clone_order_weekly', $args ) ) {
wp_schedule_event(time(), 'everyweek', 'clone_order_weekly', $args );
}
}
And here is the function to trigger the clone:
add_action ('clone_order_weekly', 'trigger_action_clone_order');
function trigger_action_clone_order( $order ) {
if ( ! is_a($order, 'WC_Order') || $order->get_order_number() == 0 ) {
return; // Exit if it's not a WC_Order object or the order number is 0
}
// For testing (Send email with the order ID)
$recipients = '[email protected]';
$subject = 'Scheduled Cron Job from Order number #'.$order->get_order_number();
$message = 'This is a test mail from a scheduled Cron Job on Order number #'.$order->get_order_number();
wp_mail($recipients, $subject, $message);
// Give a flag to the parent order
$order->add_meta_data( '_is_recurring_order', 'true');
$order->add_meta_data( '_is_recurring_order_weekly_parent', 'true');
$order->add_meta_data( '_is_recurring_order_child_created', date("d-m-Y H:i:s"));
$order->save();
// Create the child order (clone the parent order)
$child_order = mutiara_woocommerce_order_clone( $order_id = $order->get_id(),
$frequency = 'everyweek');
if ( $child_order && is_a($child_order, 'WC_Order') ) {
// Get the child order ID
$child_order_id = $child_order->get_id();
// Store the child order ID on the parent order
$order->add_meta_data( '_recurring_order_child_id', $child_order_id );
$order->save();
}
}
The function mutiara_woocommerce_order_clone
is where the cloning logic. In the beginning, everything went well, then after WP update, the clone triggers every 2 mins with cloning order ID 0
(strangely only on Fridays), that's why on the trigger_action_clone_order
I added an extra check:
if ( ! is_a($order, 'WC_Order') || $order->get_order_number() == 0 ) {
return; // Exit if it's not a WC_Order object or the order number is 0
}
It works, as in no more clone triggers every 2 mins on Fridays.. but I see "Cron missing schedule" and the clone stops working.
What could be the issue? And how can I fix this?