WordPress REST API - Allow anyone to POST

半城伤御伤魂 提交于 2019-12-05 10:00:33
doublesharp

There are three different options to authenticate to the REST API:

  1. Cookie - this is what you are using now
  2. OAuth - requires the OAuth plugin and embedding key on the front end
  3. Basic - requires embedding the username/password on the front end

See the documentation on using these methods here: http://v2.wp-api.org/guide/authentication/.

There are obvious security risks when embedding the auth info on the front end, which is required by OAuth and Basic as anyone will be able to authenticate as the user the key is associated with. I'm not familiar enough with the WP OAuth plugin to know how granularly you can control access, but I don't think you really can.

The easiest solution is to write your own method outside the REST API to handle these updates (or contribute to the project to make unauthenticated requests possible). I wrote up a guide for Creating AJAX Functions on my website, but basically you want to attach a function to the wp_ajax_nopriv_* hook, where the * is the "action" parameter of your request. In your hooked PHP function you handle the post insertion and respond with JSON (you could even match the WP REST API format).

PHP

// insert new post
function create_post_33741541() {
    // use the $_POST to create your post
    $args = array(
         'post_title' => isset( $_POST['title'] )? $_POST['title'] : 'Empty Title',
         // more parameters....
    );
    $post_id = wp_insert_post( $args );

    // make a response
    $response = array( 'post_id' => $post_id, 'message' => 'post created!' );

    // set the content type and return json encode response, then exit
    header( 'Content-type: application/json' );
    die( json_encode( $response ) );
}
// use wp_ajax_nopriv to access from front end
add_action( 'wp_ajax_nopriv_create_post_33741541', 'create_post_33741541' );
add_action( 'wp_ajax_create_post_33741541', 'create_post_33741541' );

JavaScript

function createThePost(){
    var data = {
        // use the part after "wp_ajax_nopriv" as the action
        action: 'create_post_33741541'
        title: 'Your title',
        // other params
    };

    $.ajax({
        method: "POST",
        url: ajaxurl,
        data: data,
        // your handlers
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!