每次创建新帖子时,我都需要执行curl请求。
为了实现这一点,我使用了以下代码,非常类似于one provided in the Codex.
add_action(\'transition_post_status\', \'wpse120996_do_curl\', 10, 3);
function wpse120996_do_curl($new_status, $old_status, $post)
{
$post_ID = $post->ID;
error_log(" [ ". date("Y-m-d H:i:s") . " ] ". $post_ID . " : " .
$old_status . " -> " . $new_status . "\\n", 3, $_SERVER[\'DOCUMENT_ROOT\'] . "/log.txt");
if ($post->post_type != \'post\' || $new_status != \'publish\' || $old_status != \'draft\') {
return;
}
$url = \'https://api.telegram.org/bottoken/sendMessage\';
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => \'Codular Sample cURL Request\',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
chat_id => \'@mychatid\',
text => print_r($post, true)
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
error_log(" [ ". date("Y-m-d H:i:s") . " ] sending post with ID = ". $post_ID ."\\n", 3, $_SERVER[\'DOCUMENT_ROOT\'] . "/log.txt");
if (!curl_exec($curl)) {
die(\'Error: "\' . curl_error($curl) . \'" - Code: \' . curl_errno($curl));
}
// Close request to clear up some resources
curl_close($curl);
}
问题是每次保存帖子时都会调用两次wpse120996\\u do\\u curl(),如下面的屏幕截图所示。
如何在保存帖子时仅获取一个函数调用?
我在Wordpress 4.8.2中运行此代码,没有安装插件。
编辑:在代码中添加error\\u log()后,查看日志。txt,似乎只调用了一次wpse120996\\u do\\u curl(),但不幸的是,完成了两个curl请求。
log.txt content
[ 2017-10-13 16:31:31 ] 109 : new -> auto-draft
[ 2017-10-13 16:31:37 ] 109 : auto-draft -> draft
[ 2017-10-13 16:32:05 ] 109 : draft -> publish
[ 2017-10-13 16:32:05 ] sending post with ID = 109
[ 2017-10-13 16:32:06 ] 110 : new -> inherit
最合适的回答,由SO网友:Frank P. Walentynowicz 整理而成
替换此行:
if ($old_status != \'draft\' || $new_status != \'publish\') {
使用:
if ( $post->post_type != \'post\' || $new_status != \'publish\' || $old_status != \'auto-draft\' ) {
您想在上运行代码
post
转换自
auto-draft
到
publish
, 这只会发生一次
post
已创建。
UPDATE
问题出在代码的这一部分:
$resp = curl_exec($curl);
error_log(" [ ". date("Y-m-d H:i:s") . " ] sending post with ID = ". $post_ID ."\\n", 3, $_SERVER[\'DOCUMENT_ROOT\'] . "/log.txt");
if (!curl_exec($curl)) {
die(\'Error: "\' . curl_error($curl) . \'" - Code: \' . curl_errno($curl));
}
您正在呼叫
curl_exec($curl)
两行!首先:
$resp = curl_exec($curl);
其次:
if (!curl_exec($curl)) {
更改您的
if
声明收件人:
if (!$resp) {