You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress定时推送随机文章通知故障排查及代码修正请求

WordPress定时推送随机文章通知的问题排查与修复

核心问题梳理

  • 函数作用域错误:send_notification函数被定义在wp_schedule_event的if代码块内部,导致add_action无法正确识别该函数,调度钩子绑定失败。
  • 缺省分钟级调度周期:WordPress默认没有minutely(每分钟)的调度间隔,必须手动注册该周期。
  • 未处理空文章数组:get_posts可能返回空数组(比如站点无已发布文章),直接访问$random_post[0]会触发致命错误。
  • HTTP请求头格式错误:Content-Type的值应为小写的application/json,而非Application/Json,部分API会严格校验头信息格式。
  • 无错误日志记录:原代码仅捕获错误但未留存记录,无法定位推送失败的具体原因。

修正后的完整代码

// 注册每分钟的调度间隔
add_filter('cron_schedules', 'add_minutely_cron_schedule');
function add_minutely_cron_schedule($schedules) {
    $schedules['minutely'] = array(
        'interval' => 60, // 60秒 = 1分钟
        'display'  => __('每一分钟'),
    );
    return $schedules;
}

// 初始化调度事件
function setup_notification_cron() {
    if (!wp_next_scheduled('send_notification')) {
        wp_schedule_event(time(), 'minutely', 'send_notification');
    }
}
add_action('wp', 'setup_notification_cron');

function send_notification() {
    $end_point = 'https://api.webpushr.com/v1/notification/send/segment';
    
    // 获取已发布的随机文章
    $args = array(
        'posts_per_page' => 1,
        'orderby'        => 'rand',
        'post_status'    => 'publish' // 仅获取已发布状态的文章
    );
    $random_post = get_posts($args);
    
    // 没有可推送的文章时直接终止并记录日志
    if (empty($random_post)) {
        error_log('定时推送:未找到可推送的已发布文章');
        return;
    }
    
    $post = $random_post[0];
    $body = array(
        'title'      => $post->post_title,
        'message'    => '快来看看这篇文章!',
        'target_url' => get_permalink($post->ID),
        'segment'    => array(489294) // 目标用户分组ID
    );
    
    $response = wp_remote_post($end_point, array(
        'method'  => 'POST',
        'timeout' => 45,
        'headers' => array(
            'Content-Type'       => 'application/json', // 修正为标准小写格式
            'webpushrKey'        => 'XXXXXXXXX', // 替换为你的webpushr密钥
            'webpushrAuthToken'  => '29009' // 替换为你的webpushr认证令牌
        ),
        'body'    => json_encode($body),
    ));
    
    // 记录推送日志便于排查问题
    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        error_log('定时推送失败:' . $error_message);
    } else {
        $response_body = wp_remote_retrieve_body($response);
        error_log('定时推送成功,响应内容:' . $response_body);
    }
}
add_action('send_notification', 'send_notification');

额外注意事项

  • 确认WordPress的Cron功能正常运行:可安装WP Crontrol插件查看、测试Cron事件状态。
  • 替换代码中的webpushrKey和webpushrAuthToken为你在webpushr平台获取的真实密钥。
  • 检查segment中的分组ID(489294)是否正确,确保该分组存在且有订阅用户。
  • 开启WordPress调试日志:在wp-config.php中添加define('WP_DEBUG_LOG', true);,可通过wp-content/debug.log查看推送相关日志。

内容的提问来源于stack exchange,提问作者Safayet hossain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:50:26