-
-
Save zoonderkins/0c8d9dc2d721f2ee767dbdd4ea380d30 to your computer and use it in GitHub Desktop.
Get all WordPress posts with JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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