Skip to content

Instantly share code, notes, and snippets.

@JackEdwardLyons
Last active June 9, 2021 02:43
Show Gist options
  • Save JackEdwardLyons/edf805de3dd91d14a7a0da8b605a35f4 to your computer and use it in GitHub Desktop.
Save JackEdwardLyons/edf805de3dd91d14a7a0da8b605a35f4 to your computer and use it in GitHub Desktop.
Get all WordPress posts with JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<pre id="state">Loading posts ...</pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js" integrity="sha256-lrZTgsdM1iVdRigETFOU8u8/BmLX1ysQ8bzrULbuVFU="
crossorigin="anonymous"></script>
<script>
let state = {
posts: [],
baseUrl: 'https://cors-anywhere.herokuapp.com/https://jacklyons.me/wp-json/wp/v2/posts',
perPage: '?per_page=10',
wpFetchHeaders: {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Expose-Headers': 'x-wp-total'
}
}
}
async function getNumPosts() {
const { headers } = await axios(`${state.baseUrl}${state.perPage}`, state.wpFetchHeaders)
return headers['x-wp-totalpages']
}
async function fetchPosts(numPages) {
const posts = []
for (let page = 1; page <= numPages; page += 1) {
const post = axios.get(`${state.baseUrl}${state.perPage}&page=${page}`, state.wpFetchHeaders)
posts.push(post)
}
await axios.all(posts).then((response) => {
const postData = response.map(res => res.data)
state.posts = postData.flat()
}).catch(e => console.log('error fetching posts: ', e))
return true
}
state.posts = getNumPosts()
.then(numPosts => fetchPosts(numPosts))
.then((data) => {
console.log('data ', state)
document.getElementById('state').innerText = JSON.stringify(state, null, 4)
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment