WP_Query result in form of Rest API results

All we need is an easy explanation of the problem, so here it is.

This is simple posts result array.

$query = new WP_Query( array( 'post_type' => 'post' ) );
$posts = $query->posts; // returns simple array of data

Is there a way to get the results from wp-json/wp/v2/posts/?_embed without making extra request to server to pull json and then decode to php array?

Looking for something like that:

$posts = $query->rest_posts(); // for example ??

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I think we can simplify it with:

$request  = new WP_REST_Request( 'GET', '/wp/v2/posts' );
$response = rest_do_request( $request );
$data     = rest_get_server()->response_to_data( $response, true );

by using rest_do_request().

Method 2

After digging into source code ended up with this solution. Works for me, might be useful to others as well.

function get_rest_items_query($post_type, $posts_per_page, $orderby = 'date', $order = 'desc') {

    $result = array();
    $args = array( 'post_type' => $post_type, 'posts_per_page' => $posts_per_page, 'orderby' => $orderby, 'order' => $order );
    $posts = get_posts($args);

    $ids = implode(',', wp_list_pluck($posts, 'ID'));

    // request
    $restRequest = new WP_REST_Request('GET', '/wp/v2/' . $post_type  );
    $restRequest->set_param('include', $ids);
    // response
    $response = rest_do_request( $restRequest );
    // _embed
    $rest = rest_get_server()->response_to_data( $response, true );

    $result['posts'] = $rest;

    return $result;
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply