We are using javascript fetch() api to fetch posts from the WordPress Rest API.
fetch() api returns Promise() so I have decided to use async/await instead of callback. So that I can easily assign responsed data from the WP Rest API to the local arrays and reuse them.
async function getBlogPosts() {
try {
const response = await fetch('https://webmarket101.net/wp-json/wp/v2/posts');
const posts = await response.json();
const blogPosts = posts.map((post) => {
return {
title: post.title.rendered,
content: post.excerpt.rendered,
image: post.fimg_url,
url: post.link
};
});
return blogPosts;
} catch (error) {
console.error('Error retrieving blog posts:', error);
return [];
}
}
We are also using javascript arrays.map function to create new blogPosts array with new item from raw array responsed received from the API.
Javascript arrays.map return new array, it will process array item with emply element and it doesn’t change the original array.
Comments
This is helpful, but how can we find the max_num_posts in the header to determine if we have more than one page of posts?
Following up, I believe this is the answer:
“`
totalPages = await response.headers.get(‘x-wp-totalpages’);
Thanks for your comments.