Search code examples
wordpresswordpress-rest-api

WP REST API v2: Getting posts by post ids


I'm trying to get all posts by ID's using WP REST API. As per the documentation, we can use filter to use WP Query arguments. Using this with posts end point returns all the posts.

http://demo.wp-api.org/wp-json/wp/v2/posts/?filter[posts__in]=470,469

Solution

  • For the v2 of WP REST API use this format-

    http://demo.wp-api.org/wp-json/wp/v2/posts?include[]=470&include[]=469

    If you want custom coding then,

    You can retrieve single post by id like

    http://demo.wp-api.org/wp-json/wp/v2/posts/?filter[p]=470
    

    But as per support its will not work for multiple post.

    https://github.com/WP-API/WP-API/issues/1368
    

    So you can ran a loop and get one by one.

    But for multiple you have to put an function

    add_filter('rest_query_vars', 'custom_rest_query_vars');
    function custom_rest_query_vars($query_vars) {
      $query_vars = array_merge( $query_vars,    array('post','post__in','type','id') );
      return $query_vars;
    }
    

    Then you have to run

    +filter[post__in][]=470&filter[post__in][]=469