WordPress Rest API 获取所有帖子
WordPress Rest API get All Posts
我正在使用以下方式获取帖子
http://demo.wp-api.org/wp-json/wp/v2/posts
这默认给我 10 个帖子,这在文档中提到。
但我想要所有的帖子而不必跟踪分页。
这可能吗?
如果没有,我可以 运行 JavaScript 循环获取所有帖子吗?
谢谢。
您可以使用 wp_remote_retrieve_body($url) 或 wp_remote_post($url ) 获取 post 数据而不是剩余 API 用法。 wp_remote 函数独立于默认分页。
解决这个问题的一种方法是 RxJS
我们将构建一个小型 Observable 流,它将:
- 输出全部post数据
- 不强制我们事先知道 post 或页面的总数
- 不强制在分页上下文中跟踪 "where we're at"
我们将使用的库:
您的环境和用例会有所不同,对于这个例子,我将在 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),
)
资源
- RunKit example with the code above(唯一的区别是在 RunKit 示例中导入 RxJS v5,因为 v6 尚不可用,但 API 是 no此示例不同)
- RxJS In Depth - Ben Lesh(视频,主要维护者对 RxJS 的良好介绍)
- The introduction to Reactive Programming you've been missing (@andrestaltz 介绍 RxJS 的最佳文本资源)
- https://www.learnrxjs.io/
- Destructuring objects as function parameters in ES6
- Arrow Functions on MDN(检查基本和高级语法)
大型查询会影响网站性能,因此 per_page
的上限为 100 条记录。如果您希望检索超过 100 条记录,例如构建所有可用类别的客户端列表,您可以发出多个 API 请求并在您的应用程序中合并结果。 See this page for a complex explanation
您可以在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
}
我正在使用以下方式获取帖子
http://demo.wp-api.org/wp-json/wp/v2/posts
这默认给我 10 个帖子,这在文档中提到。
但我想要所有的帖子而不必跟踪分页。
这可能吗?
如果没有,我可以 运行 JavaScript 循环获取所有帖子吗?
谢谢。
您可以使用 wp_remote_retrieve_body($url) 或 wp_remote_post($url ) 获取 post 数据而不是剩余 API 用法。 wp_remote 函数独立于默认分页。
解决这个问题的一种方法是 RxJS
我们将构建一个小型 Observable 流,它将:
- 输出全部post数据
- 不强制我们事先知道 post 或页面的总数
- 不强制在分页上下文中跟踪 "where we're at"
我们将使用的库:
您的环境和用例会有所不同,对于这个例子,我将在 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),
)
资源
- RunKit example with the code above(唯一的区别是在 RunKit 示例中导入 RxJS v5,因为 v6 尚不可用,但 API 是 no此示例不同)
- RxJS In Depth - Ben Lesh(视频,主要维护者对 RxJS 的良好介绍)
- The introduction to Reactive Programming you've been missing (@andrestaltz 介绍 RxJS 的最佳文本资源)
- https://www.learnrxjs.io/
- Destructuring objects as function parameters in ES6
- Arrow Functions on MDN(检查基本和高级语法)
大型查询会影响网站性能,因此 per_page
的上限为 100 条记录。如果您希望检索超过 100 条记录,例如构建所有可用类别的客户端列表,您可以发出多个 API 请求并在您的应用程序中合并结果。 See this page for a complex explanation
您可以在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
}