首页 > 解决方案 > 如何防止 cURL 在 WP 函数中被触发两次?

问题描述

发布 WordPress 帖子时,有时会多次调用 publish_post 挂钩。因此函数 send_webhook 也被多次触发。

我试图用一个全局变量来阻止它,但这似乎不起作用。我认为这是因为函数本身被多次调用。

这是我的代码:

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;
    }
}

如何防止 cURL 在例如 300 秒的时间段内被多次触发,即使该函数被多次调用?也许以某种方式将帖子标题存储在一个变量中,然后检查它是否已经使用?有任何想法吗?

标签: phpwordpress

解决方案


您可以使用post_meta来验证之前是否调用过该函数。如果不是(或者已经过了 300 秒),执行 api 调用并保存当前时间:

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'));
    }
}

推荐阅读