Skip to content

Instantly share code, notes, and snippets.

@jorgeacortes
Last active August 15, 2020 15:20
Show Gist options
  • Save jorgeacortes/94801ebe076d990a1fa0d587d1d6cd97 to your computer and use it in GitHub Desktop.
Save jorgeacortes/94801ebe076d990a1fa0d587d1d6cd97 to your computer and use it in GitHub Desktop.
Functions to retrieve a Wordpress post data.
/* Retrieves Wordpress post data of the post number idx from a domain.
* Note: idx is the index of the response array of posts.
*/
async function fetchWpPost(domain, idx) {
try {
var ret = {};
const response = await fetch('https://'+domain+'/wp-json/wp/v2/posts')
.then(response => response.json())
.then(data => {
ret.title = data[idx].title.rendered;
ret.link = data[idx].link;
ret.text = data[idx].excerpt.rendered;
ret.id = data[idx].id;
ret.date = data[idx].date;
ret.img = "/wp-json/wp/v2/media?parent="+ret.id;
})
return ret;
} catch(e) {
console.log(e)
}
}
/* Retrieves the image url of the blog post id */
async function fetchWpPostImage(domain, id) {
try {
var ret = "";
const response = await fetch('https://'+domain+'/wp-json/wp/v2/media?parent='+id)
.then(response => response.json())
.then(data => {
ret = data[0].source_url;
})
return ret;
} catch(e) {
console.log(e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment