DEV Community

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

Posted on

2

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

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 🙂

API Trace View

Struggling with slow API calls? 👀

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs