WordPress Rest API 获取所有帖子

问题描述 投票:0回答:5

我正在使用以下内容来获取帖子

http://demo.wp-api.org/wp-json/wp/v2/posts

默认情况下,这会给我 10 个帖子,文档中提到了这一点。

但我想要所有帖子而不必跟踪分页。

这可能吗?

如果没有,我可以运行 JavaScript 循环来获取所有帖子吗?

谢谢。

wordpress wordpress-rest-api
5个回答
0
投票

解决此问题的一种方法是使用 RxJS

我们将构建一个小型 Observable 流,它将:

  • 输出所有post数据
  • 不强迫我们事先知道帖子总数或页数
  • 不强迫在分页上下文中跟踪“我们在哪里”

我们将使用的库:

  • Axios(为了简化 HTTP GET,因为它在节点和浏览器环境中都可以工作)
  • RxJS v6(目前是 Alpha 版本,但这里的 API 与 RxJS 5 相同)

您的环境和用例会有所不同,在本示例中,我将处于 Node 环境中。

/**
 *      This will get all posts from a default WordPress REST API
 *      First we see how many pages there are
 *      Then we make subsequent XHR requests (via Axios)
 *      That paginate through every page of posts
 */

// Importing Axios for simple AJAX request
const axios = require('axios')

// Importing RxJS @ v6.0.0-alpha.3
const { Observable, from, range } = require('rxjs')
const { switchMap, concatMap } = require('rxjs/operators')

const endpoint = 'http://demo.wp-api.org/wp-json/wp/v2/posts'

/**
 *      This sets up the initial request and the Observable stream
 *      In the return from the endpoint, the Axios request headers will have x-wp-totalpages,
 *      which gives us... the total pages of posts ;)
 */
const posts$ = Rx.Observable.from(axios.get(endpoint))
    /**
     *     We now know the total number of pages,
     *     so we'll switch to a new Observable that is just a range of numbers
     *     We'll start with 1, and end with whatever the total number of pages is
     *     This gives us a stream of 1--n--n--n... (example: 1, 2, 3, 4...)
     */
    .switchMap((
        { headers }, // using ES6 function header destructuring and arrow functions here
    ) => Rx.Observable.range(1, Number(headers['x-wp-totalpages'])))
    /**
     *     We can now paginate through all posts, getting 10/page
     *     concatMap will fire off a request, waits until it completes, and then fire the next one
     *     In each subsequent firing, we ask for the next page of posts
     */
    .concatMap(page =>
        axios.get(endpoint, {
            params: {
                page,
            },
        }),
    )
    .subscribe(
        // data here is an Array of WordPress Posts, tacking .length shows us how many per page we are getting
        ({ data }) => console.log(data.length),
        err => console.log('Oh no, an error!', err),
    )

资源


0
投票

您可以使用 wp_remote_retrieve_body($url)wp_remote_post($url) 来获取帖子数据,而不是使用其他 API。 wp_remote 函数独立于默认分页。


0
投票

您可以在node.js中使用此功能

const getAllPosts = async (wordpressUrl) => {
  const url = `${wordpressUrl}/wp-json/wp/v2/posts?per_page=100`

  const maxPages = 50
  let page = 1
  let text
  const responses = []
  while (true) {
    const urlWithPage = `${url}&page=${page}`
    const res = await fetch(urlWithPage)
    text = await res.text()
    text = text.trim()
    if (res.status !== 200) {
      break
    }
    if (text === '[]') {
      break
    }
    if (!text.match(/^\[/) || !text.match(/\]$/)) {
      break
    }
    text = text.replace(/^\[/, '').replace(/\]$/, '')
    responses.push(text)

    if (page > maxPages) {
      break
    }
    page++
  }

  // get all pages and join them
  if (responses.length) {
    return `[${responses.join(',')}]`
  }

  // if didn't get any valid repsonses, send the text received
  return text
}

0
投票

大型查询可能会损害网站性能,因此

per_page
的记录上限为 100 条。如果您希望检索超过 100 条记录,例如构建所有可用类别的客户端列表,您可以发出多个 API 请求并在应用程序中合并结果。 请参阅此页面了解复杂的解释


0
投票

我正在使用 typescript 以 React Native 编写一个应用程序,但是对 WordPress GET 请求结果进行分页的基本原理将是类似的。

  1. 我使用初始化为 1 的“页面”查询参数发出请求(此处抵制从 0 开始的诱惑)。
  2. 我得到“x-wp-totalpages”(通过响应标头返回),这是要接收的“页面”或帖子批次的总数
  3. 我将总页数与当前变量进行比较,并递归调用该函数,直到我的数组全部被帖子填满。

它帮助我阅读了 Wordpress REST API 分页文档

async getPosts(current = 1, allPosts = []): Promise < Types.GetPostsResult > {
  // make the api call
  const response: ApiResponse < ApiFeedResponse > = await this.apisauce.get(
    Config.API_URL + '/posts', {
      per_page: 100,
      page: current
    })

  if (!response.ok) {
    const problem = getGeneralApiProblem(response)
    if (problem) return problem
  }

  const totalNumberOfPages = Number(response.headers['x-wp-totalpages']);

  try {
    const rawPosts = response.data
    // transform the data into the format we are expecting
    const convertedPosts: PostSnapshotOut[] = rawPosts.map(convertPost)

    allPosts.push(...convertedPosts);

    if (current < totalNumberOfPages) {
      this.getPosts(current + 1, allPosts);
    }

    return {
      kind: "ok",
      posts: allPosts
    }
  } catch (e) {
    console.error(e)
    if (__DEV__) {
      console.tron.error(`Bad data: ${e.message}\n${response.data}`, e.stack)
    }
    return {
      kind: "bad-data"
    }
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.