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

如何通过WordPress REST API获取过去两周的全部文章

WordPress REST API 拉取近14天文章实现方法

要拉取过去14天内的全部文章,核心是正确使用REST API的after和before参数——这两个参数需要传入ISO8601格式的日期字符串。下面是修改后的完整实现:

核心修改点

  • 计算近14天的时间范围:生成14天前的ISO日期作为after值,当前日期作为before值
  • 用http_build_query构建请求参数,自动处理URL编码,避免拼接错误
  • 处理分页:如果14天内文章超过单页上限,循环获取所有页面

修改后的完整代码

public function get_posts_via_rest_api(): array
{
    $all_posts = [];
    $page = 1;

    // 计算近14天的时间范围,生成ISO8601格式日期(匹配站点时区)
    $two_weeks_ago = date('c', strtotime('-14 days', current_time('timestamp')));
    $current_time = date('c', current_time('timestamp'));

    try {
        do {
            // 构建请求参数
            $params = [
                'page' => $page,
                'after' => $two_weeks_ago,
                'before' => $current_time,
                'per_page' => 100, // 单页最大允许数量,减少请求次数
            ];
            $url = 'https://example.com/wp-json/wp/v2/posts?' . http_build_query($params);

            $response = wp_remote_get($url);
            
            if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
                break;
            }

            $response_body = json_decode(
                $response['body'],
                false,
                512,
                JSON_THROW_ON_ERROR
            );

            if (empty($response_body)) {
                break;
            }

            $all_posts = array_merge($all_posts, $response_body);

            // 获取总页数,判断是否需要继续请求下一页
            $total_pages = wp_remote_retrieve_header($response, 'X-WP-TotalPages');
            $page++;
        } while ($page <= $total_pages);

    } catch (Exception $e) {
        error_log('Error fetching posts: ' . $e->getMessage());
        return [];
    }

    return $all_posts;
}

关键细节说明

  • 时区匹配:用current_time('timestamp')获取WordPress站点时区的时间戳,确保日期范围和文章发布时间一致
  • 参数合规:date('c')生成标准ISO8601格式(如2024-05-20T12:30:00+08:00),完全符合REST API参数要求
  • 分页优化:设置per_page=100(API允许的最大值)减少请求次数,通过响应头X-WP-TotalPages自动判断是否还有未获取的页面
  • 错误简化:优化错误日志输出,更清晰定位问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:24:31