Modify the following function so that it will wait for 5 seconds after order creation before executing. use wp_schedule_single_event to make it a cron job that doesn’t block other code from running. add_action( ‘woocommerce_new_order’, ‘st_Send_invoice_for_pending_payment’, 20, 1 ); function st_Send_invoice_for_pending_payment( $order_id ) { // Get the order instance. $order = wc_get_order( $order_id ); if ( is_a( $order, ‘WC_Order’ ) && $order->get_status() == ‘pending’ ) { WC()->mailer()->emails[’WC_Email_Customer_Invoice’]->trigger($order_id); } }

WordPress AI Code Robot

Create WordPress code snippets for free without a developer!

{Name (First):7.3} requested the  following code from my WordPress AI Code Generator.

Modify the following function so that it will wait for 5 seconds after order creation before executing. use wp_schedule_single_event to make it a cron job that doesn't block other code from running.

add_action( 'woocommerce_new_order', 'st_Send_invoice_for_pending_payment', 20, 1 );

function st_Send_invoice_for_pending_payment( $order_id ) {
// Get the order instance.
$order = wc_get_order( $order_id );
if ( is_a( $order, 'WC_Order' ) && $order->get_status() == 'pending' ) {
WC()->mailer()->emails['WC_Email_Customer_Invoice']->trigger($order_id);
}
}

The robot generated the following code:

You can use the `wp_schedule_single_event` function to schedule your process in the future, allowing other code to execute without being blocked. Below is how you can apply this:

“`php
add_action('woocommerce_new_order', 'nm_st_Send_invoice_for_pending_payment', 20, 1);

function nm_st_Send_invoice_for_pending_payment($order_id) {
// Get the order instance.
$order = wc_get_order($order_id);
if (is_a($order, 'WC_Order') && $order->get_status() == 'pending') {
// Schedule the event to send invoice in 5 seconds after order created
wp_schedule_single_event(time() + 5, 'nm_st_execute_send_invoice', array('order_id' => $order_id));
}
}

add_action('nm_st_execute_send_invoice', 'nm_st_execute_send_invoice', 10, 1);

function nm_st_execute_send_invoice($args) {
$order_id = $args['order_id'];
WC()->mailer()->emails['WC_Email_Customer_Invoice']->trigger($order_id);
}
“`

What I did here:
I just put your invoice sending function into the scheduled event `nm_st_execute_send_invoice`. I triggered this event in 5 seconds after the order is created. I also passed necessary arguments (`order_id`) into the scheduled event. Then I added function `nm_st_execute_send_invoice` which will take `order_id` and send the invoice. It will be done 5 seconds after order creation and this function will not block other code from running.

More
CODE SNIPPETS