WordPress REST API Endpoint

I am writing an Angular WP theme and i’m trying to reduce the number of HTTP requests on the post page.

On the post page I want to list all the different taxonomies, recent posts, get the featured image and a few other things. I can do this all with individual requests with the REST API v2 plugin but that’s a lot of requests.

Read More

I was hoping to create an endpoint for my theme, parse the post slug and get it all back in one request but I can’t seem to figure it out.

I was thinking of using query string to get the slug. Here’s what I have been using to test it out:

function app_get_post($data) {
    global $wp_query;

    return [
        'test' => $data,
        'vars' => $wp_query->query_vars
    ];
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'app/v1', '/post', [
        'methods' => 'GET',
        'callback' => 'app_get_post',
    ] );
} );

Here’s what it produces:

{
test: { },
vars: [ ]
}

I did try adding the query var with a query_vars hook but it didn’t work either.

Any suggestions? Am I going about this the right way?

Related posts

3 comments

  1. So I’m learning about all this as well and haven’t met success yet but will offer my research points. I know that to tap into a Custom Post Type you would need to add show_in_rest=true to the register_post_type() array or hook into it later.

    However your example shows the use of post which I’m guessing should have show_in_rest where it is registered… I decided to check in wp-includes/post.php and it does not exist.

    // ACCESSING A CPT FROM ANYWHERE (unable to add show_in_rest=true to the register_post_type() hook into it!)
    // http://scottbolinger.com/custom-post-types-wp-api-v2/
    function sb_add_cpts_to_api( $args, $post_type ) {
        if ( 'movie' === $post_type ) {
            $args['show_in_rest'] = true;
            $args['rest_base'] = 'movie';
            // $args['rest_controller_class'] = 'WP_REST_Posts_Controller';
        }
        return $args;
    }
    add_filter( 'register_post_type_args', 'sb_add_cpts_to_api', 10, 2 );
    

Comments are closed.