php - 如何防止 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 秒的时间段内被多次触发,即使该函数被多次调用?也许以某种方式将帖子标题存储在一个变量中,然后检查它是否已经使用?有任何想法吗?
解决方案
您可以使用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'));
}
}
推荐阅读
- c++ - 如何声明线程本地的静态类数据成员?
- automapper - 如何对可能为空的属性应用 AutoMapper ValueConverters
- powershell - Set-AzureADUserLicense:无法绑定参数“AssignedLicenses”
- python - InvalidArgumentError: indices[82,0] = 69687 不在 [0, 69054)
- git - 在 git 中从远程创建功能分支的最佳方法是什么?
- java - 编写一个程序,在计算机和用户之间玩一个简单的骰子游戏。当程序运行时,一个循环应该重复 10 次
- node.js - TypeScript:在节点中将 XML 解析为 JSON 会丢失相同名称标签的顺序
- docker - 如何从大型解决方案中高效地构建多个 docker 镜像?
- python-3.x - Python:如何将 JWT 访问令牌 exp 时间与当前时间进行比较以确定它是否有效?
- php - 删除数组中重复的一对值