Skip to content

Instantly share code, notes, and snippets.

@kloh-fr
Last active December 21, 2020 18:59
Show Gist options
  • Save kloh-fr/2287a1cf840e17e5ab8436cf081201e8 to your computer and use it in GitHub Desktop.
Save kloh-fr/2287a1cf840e17e5ab8436cf081201e8 to your computer and use it in GitHub Desktop.
Get WordPress posts via API
<!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>Get WordPress posts via API</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://protonmail.com/blog/wp-json/wp/v2/posts",
perPage: "?per_page=5",
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