4

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?

  • command line or php or JS. Non authenticate user or one which requires security measures. Maybe it is just me but it is not very clear what you are asking about, at least it is not foicused. – Mark Kaplun Dec 17 '15 at 8:27
  • GET posts doesn't need authentication (at least you need to get private posts). – cybmeta Dec 17 '15 at 8:42
  • So why calling curl [mydomain]/wp-json/wp/v2/posts/ gives {"code":"rest_no_route","message":"Nessun percorso fornisce una corrispondenza tra l'URL e le modalit\u00e0 di richiesta","data":{"status":404}}%? mydomain is correct.. – Luca Reghellin Dec 17 '15 at 8:44
  • @Mark Kauplin: simply, how to retrieve a list of posts from a plugin or from the command line (curl) via the (now with v4.4) native rest api? – Luca Reghellin Dec 17 '15 at 8:53
6

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/
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.