Question

I want to try the new REST API but I'm not used to this kind of things. Basically, I want to use it to GET custom posts via ajax and show on the website frontend (I'm building an ajax product filtering system).

I can't figure out how to authenticate from php and how to test authenticating from command line.

I guess I don't need OAuth here, as for the official v2 docs, but the docs say that I would use nonce system (no problem here) from an authenticated user. Obviously, being a website script asking for posts, there's no human user authenticating in my case, so how can I do it via php or js, and in a decently secure way?

Was it helpful?

Solution

GET requests, like listing posts, doesn't need authentication at least you need to get private posts. Your problem is that you are using a route/endpoint that doesn't exist.

In WordPress 4.4, WP REST API infrastructure was merged, endpoints didn't; they will be merged in WordPress 4.5 (as WordPress 4.6 it seems endpoints are still don't included in core). You need to define your own endpoints or install the plugin to use the default endpoints it provides.

For example (not tested, just written here):

add_action( 'rest_api_init', 'cyb_register_api_endpoints' );
function cyb_register_api_endpoints() {

    $namespace = 'myplugin/v1';

    register_rest_route( $namespace, '/posts/', array(
        'methods' => 'GET',
        'callback' => 'cyb_get_posts',
    ) );

}

function cyb_get_posts() {

    $args = array(
         // WP_Query arguments
    );

    $posts = new WP_Query( $args );

    $response = new WP_REST_Response( $posts );

    return $response;

}

Then, you can get the posts:

https://example.com/myplugin/v1/posts/

OTHER TIPS

There is a WP-CLI package wp-cli/restful that opens up rest endpoints to the CLI.

Listing the custom post type like product while authenticated as an administrator is as easy as:

wp post list --post-type=product --user=admin
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top