php - WP插件中的异步php代码

标签 php curl asynchronous wordpress

需要使此代码块与其余代码异步。它会收集 wp 帖子并向我的网址发送帖子请求。该插件应该异步运行,并且不会妨碍 wordpress 网站的运行。

for ($x=0; $x<=n; $x++) {
$data = posts[$x];
$ch = curl_init('http://myurl.com/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'ACCEPT: application/json',
'Content-Length: ' . strlen($data))
);

$result = curl_exec($ch);
curl_close($ch);
}

最佳答案

在 WordPress 中处理异步请求的正确方法是使用 WP-Cron 来安排事件。您可以安排它运行一次,也可以每隔一段时间运行一次。查看一些设置指南 here .要检查的两个主要功能是 wp_schedule_event()wp_schedule_single_event() .

但要记住的一件事是,因为您的代码仅在有请求时运行,如果流量较低,则您安排的事件可能不会按预期运行。我在我的网站上写了一篇关于如何结合使用 crontab 和 WP-Cron 来更准确地安排事件的文章:http://justinsilver.com/technology/wordpress/disable-wp-cron-wordpress/ .

关于php - WP插件中的异步php代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26826780/

相关文章:

php - 我的 session 类应该是静态的吗?

php - NuSoap soapClient 调用出现 "Premature end of data in tag html"错误

php - 搜索结果和后退按钮/HTML 表单

http - Node.js HTTP GET 不返回所有数据

ubuntu - 无法通过curl使用nova,需要身份验证

android - NetworkOnMainThreadException

Android异步API设计

PHP POST 到 URL,用户被重定向

PHP 无法加载 php_curl.dll 扩展

javascript - AngularJS - 使用 ng-click 在新窗口中打开链接