WordPress定时发布文章时Telegram通知插件异常求助
问题分析与解决方案
你的定时发布文章通知触发但异常,核心问题出在钩子选择不当和状态判断逻辑冗余,导致定时文章在被设置为待发布(future)时就触发了通知,而非真正发布完成时。
问题点拆解
transition_post_status钩子触发时机错误:当设置文章定时发布时,文章状态会从draft/pending变为future,此时你的代码就会触发通知——但这时候文章还没真正发布,不仅链接可能异常,内容也可能不是最终版本。- 状态判断逻辑重复且不准确:
invia_notifica_telegram里的条件同时判断publish和future,但future状态的文章还未正式对外发布,此时执行通知毫无意义。 - 缺少错误排查机制:发送Telegram的代码没有错误日志,无法定位请求失败的具体原因(比如服务器禁用
file_get_contents、token/chat_id错误等)。
修复方案
- 改用专属钩子
publish_future_post:这个钩子是WordPress专门为定时文章发布完成时触发的,只会在文章从future变为publish时执行,精准匹配需求。 - 简化状态判断逻辑:只在文章状态为
publish时执行通知,避免无效触发。 - 添加错误日志:方便排查Telegram请求失败的问题。
- 优化代码调用:直接使用传入的
$post对象获取数据,减少不必要的函数调用。
修正后的完整代码
// 使用定时文章发布完成的专属钩子 add_action('publish_future_post', 'invia_notifica_telegram_schedulato', 10, 1); function invia_notifica_telegram_schedulato($post_id) { $post = get_post($post_id); // 仅处理正式发布的文章 if ($post->post_status !== 'publish') { return; } invia_notifica_telegram($post); } function invia_notifica_telegram($post) { // 获取文章信息 $post_title = $post->post_title; $post_url = get_permalink($post->ID); // 提取h2内容并清理标签 preg_match('/<h2>(.*?)<\/h2>/si', $post->post_content, $matches); $h2_content = isset($matches[1]) ? wp_strip_all_tags($matches[1]) : ''; // 发送Telegram通知 invia_messaggio_telegram($post_title, $h2_content, $post_url); } function invia_messaggio_telegram($title, $h2_content, $url) { $telegram_bot_token = 'XXXXXXXX'; $telegram_chat_id = '-XXXXXXX'; // 构建消息(添加标题更清晰,适配Telegram HTML解析规则) $message = "<b>$title</b>\n\n"; $message .= $h2_content ? "$h2_content\n\n" : ''; $message .= "<a href=\"$url\">查看全文</a>"; $api_url = "https://api.telegram.org/bot$telegram_bot_token/sendMessage"; $data = array( 'chat_id' => $telegram_chat_id, 'text' => $message, 'parse_mode' => 'HTML', 'disable_web_page_preview' => false // 可选:控制是否显示链接预览 ); // 使用WordPress内置HTTP函数替代file_get_contents,兼容性更好 $response = wp_remote_post($api_url, array( 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'), 'body' => http_build_query($data), 'timeout' => 10 )); // 添加错误日志,方便排查问题 if (is_wp_error($response)) { error_log('Telegram通知发送失败: ' . $response->get_error_message()); } else { $response_body = json_decode(wp_remote_retrieve_body($response), true); if (!$response_body['ok']) { error_log('Telegram API错误: ' . $response_body['description']); } } }
额外注意事项
- 确保你的WordPress cron服务正常运行(定时文章依赖cron触发发布),可以安装插件如WP Crontrol检查cron状态。
- 替换代码中的
telegram_bot_token和telegram_chat_id为你自己的有效信息。 - 使用
wp_remote_post替代file_get_contents是因为WordPress内置的HTTP函数更兼容不同服务器环境,且自带错误处理。
内容的提问来源于stack exchange,提问作者Marco Talluto
相关产品推荐
相关产品推荐

