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

  • David McKnight
    Reply

    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?

  • David McKnight
    Reply

    Following up, I believe this is the answer:
    “`
    totalPages = await response.headers.get(‘x-wp-totalpages’);

  • Derick
    Reply

    Thanks for your comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign In

Register

Reset Password

Please enter your username or email address, you will receive a link to create a new password via email.