Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 873
Callum Avatar asked Jan 20 '26 05:01

Callum


1 Answers

you should pass the parameter

function app_get_post($data) {

    return [
        'test' => $data["postid"]        
    ];
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'app/v1', '/post/(?P<postid>\d+)', [
        'methods' => 'GET',
        'callback' => 'app_get_post',
    ] );
} )

refer http://wiki.workassis.com/wordpress-create-rest-api/ for example

like image 139
Bikesh M Avatar answered Jan 22 '26 21:01

Bikesh M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!