questions

How to prevent cURL being fired twice in a WP function?

Rate this post

When a WordPress post is published, the publish_post hook is sometimes called multiple times. Therefore the function send_webhook is also triggered multiple times.

I tried to prevent it with a global variable, but this does not seem to work. I think that’s because the function itself is called multiple times.

This is my code:

add_action('publish_post', 'send_webhook');
function send_webhook($post_id) {
    global $ss_done;
    if (!isset($ss_done)) {
        $url = 'https://hook.integromat.com/wy41cb1vlsfi7m1dfef63sxec3wotdnr';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_exec($ch);
        curl_close($ch);
        $ss_done = true;
    }
}

How can I prevent cURL being triggered multiple times in, for example a time period of 300 seconds, even when the function is called multiple times? Maybe somehow store the post title in a variable and then check if its already used? Any ideas?

 

✔️Solution:

You can use post_meta to validate if the function has been called before. If it wasn’t (or if 300 seconds has passed), perform the api call and save the current time:

add_action('publish_post', 'send_webhook');
function send_webhook($post_id) {
    $last = get_post_meta($post_id, 'integromat_webhook_sent', true);
    if (empty($last) || (strtotime('now') - strtotime($last)) > 300  ) {
        $url = 'https://hook.integromat.com/wy41cb1vlsfi7m1dfef63sxec3wotdnr';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_exec($ch);
        curl_close($ch);
        update_post_meta($post_id, 'integromat_webhook_sent', strtotime('now'));
    }
}

Leave a Reply

Your email address will not be published.

Back to top button