Search code examples
phpwordpresswoocommercehook-woocommercezohobooks

Avoid a hooked function to be triggered multiples times in WooCommerce


I have included code in my WordPress plugin file to sync data with Zoho Books whenever an WooCommerce order is created or updated. However, I am experiencing an issue where this function is triggered multiple times during order updates or creation, resulting in multiple invoices being created in Zoho Books. Additionally, in the provided sample code, the email notification is also being triggered multiple times when an order is created or updated. I would greatly appreciate any assistance in resolving this problem.

add_action('woocommerce_update_order', 'my_function');
add_action('woocommerce_new_order', 'my_function');
function my_function($order_id) {
    send_email_test();
}

function send_email_test() {
    $to = 'ajaypartap92@gmail.com'; // Replace with the recipient's email address
    $current_time = date('Y-m-d H:i:s');
    $subject = $current_time.'Example Subject'; // Replace with the subject of the email
    $message = 'Hello, this is an example email.'; // Replace with the content of the email
    $headers = array(
        'Content-Type: text/html; charset=UTF-8', // Set the email content type as HTML
    );

    // Send the email
    $result = wp_mail($to, $subject, $message, $headers);

    // Check if the email was sent successfully
    if ($result) {
        echo 'Email sent successfully.';
    } else {
        echo 'Email sending failed.';
    }
}



Solution

  • To avoid multiple triggers on action hooks, you can simply use WordPress did_action() as follows:

    add_action('woocommerce_update_order', 'my_function');
    add_action('woocommerce_new_order', 'my_function');
    function my_function($order_id) {
        if( did_action('woocommerce_update_order') == 1 || did_action('woocommerce_new_order') == 1 ) {
            send_email_test();
        }
    }
    

    This time, you should receive just one email notification on order creation or update.