WordPress Rest API 获取所有帖子

标签 wordpress wordpress-rest-api

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

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

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

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

这可能吗?

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

谢谢。

最佳答案

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

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

  • 输出所有发布数据
  • 不要强制我们事先知道帖子总数或页数
  • 不强制在分页上下文中跟踪“我们所处的位置”

我们将使用的库:

  • 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),
    )

资源

关于WordPress Rest API 获取所有帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48494711/

相关文章:

css - 如何将图像与 anchor 文本并排对齐?

php - WooCommerce:对旧(已完成)订单加税

php - 无法使用 WP REST API 2.0 插件通过基本身份验证进行身份验证

php - 如何重定向除登陆页面之外的子目录?

php - WordPress header 位置重定向

javascript - 如何在 Gutenberg 中使用序列化数据?

php - 使用rest api创建post wordpress.com

powershell - 从 rest API : Best practice 获取页面结果

json - 使用 Alamofire 4 解析嵌套的 JSON

html - 可以为一个元素制作一个独特的(single-product.php)页面吗?