DEV Community

loading...
Cover image for How to get all WordPress posts from the WP API in just two steps

How to get all WordPress posts from the WP API in just two steps

ermal96 profile image Ermal Vrapi ・1 min read

Hello Everyone ✋
On my work, I was building a Gutenberg block to get all the posts and make with them a slider very simple thing 😝 but the problem starts when I was trying to show all posts on a dropdown where the client can choose the posts that want to show on the slider.

So if you have a case similar to me the code below will work just fine.

The first thing we will need to make a simple request and get the total amount of posts from WordPress.

   fetch('https://example.com/wp-json/wp/v2/posts?per_page=10', {
    }).then((response) => { 
        getAllPosts(response.headers.get('X-WP-Total'));
    });
Enter fullscreen mode Exit fullscreen mode

The second thing for sure we will need to create the getAllPosts function which is going to request all posts.

const getAllPosts = (allPosts) => {

 fetch(`https://example.com/wp-json/wp/v2/posts?per_page=${allPosts}`)
  .then((response) => {
    return response.json();
 })
 .then((posts) => {
  console.log(posts);
 });

}
Enter fullscreen mode Exit fullscreen mode

Now you can check your console to see if all the posts are present.


If you have any questions, comments or feedback to improve, please just leave a comment 🙂

Discussion (0)

pic
Editor guide