Fetch All Posts (Including Those Using a Custom Post Type) With Wordpress API

With the Wordpress API, we can use the following request to get all posts of the default ‘post’ type:

http://example.com/wp-json/wp/v2/posts

Supposing the ‘books’ and ‘movies’ custom post types have been created, we can get all posts in each custom post type with the following requests:

http://example.com/wp-json/custom/v1/books
http://example.com/wp-json/custom/v1/movies

Is there a similar request that can be made to obtain all the above posts, meaning those that use the default ‘post’ post type as well as those that use the ‘books’ and ‘movies’ custom post types?

1 Answer
1

I ended up extending the API like suggested in the comments to my question, although I was hoping there was a default route that fetched all posts of all post types. Apparently, there isn’t.

So here’s my solution:

add_action( 'rest_api_init', 'custom_api_get_all_posts' );   

function custom_api_get_all_posts() {
    register_rest_route( 'custom/v1', '/all-posts', array(
        'methods' => 'GET',
        'callback' => 'custom_api_get_all_posts_callback'
    ));
}

function custom_api_get_all_posts_callback( $request ) {
    // Initialize the array that will receive the posts' data. 
    $posts_data = array();
    // Receive and set the page parameter from the $request for pagination purposes
    $paged = $request->get_param( 'page' );
    $paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1; 
    // Get the posts using the 'post' and 'news' post types
    $posts = get_posts( array(
            'paged' => $paged,
            'post__not_in' => get_option( 'sticky_posts' ),
            'posts_per_page' => 10,            
            'post_type' => array( 'post', 'books', 'movies' ) // This is the line that allows to fetch multiple post types. 
        )
    ); 
    // Loop through the posts and push the desired data to the array we've initialized earlier in the form of an object
    foreach( $posts as $post ) {
        $id = $post->ID; 
        $post_thumbnail = ( has_post_thumbnail( $id ) ) ? get_the_post_thumbnail_url( $id ) : null;

        $posts_data[] = (object) array( 
            'id' => $id, 
            'slug' => $post->post_name, 
            'type' => $post->post_type,
            'title' => $post->post_title,
            'featured_img_src' => $post_thumbnail
        );
    }                  
    return $posts_data;                   
} 

The http request will look like this:

http://example.com/wp-json/custom/v1/all-posts

or, if you’re targeting a specific page of results, like this:

http://example.com/wp-json/custom/v1/all-posts?page=2

Leave a Comment