WordPress REST API - 允许任何人 POST

WordPress REST API - Allow anyone to POST

我正在 WordPress 上构建一个应用程序,它需要一个简单的前端表单,任何人都可以在其中提交需要保存在数据库中的信息。我试图通过 REST API 来处理这个问题。 (由于应用程序的性质,提交此信息时不能进行任何页面重定向。)

我在设置 REST API (v2) 时没有问题,因此我可以提交 post。当我登录 WordPress 时效果很好。当我在未登录 WordPress 的情况下尝试填写表格时,收到错误消息。

Failed to load resource: the server responded with a status of 403 (Forbidden)

如何设置 API 以在未经身份验证的情况下接收来自任何人的 POST?

这是我的 javascript:

$( '#post-submission-form' ).on( 'submit', function(e) {
    e.preventDefault();
    var title = $( '#post-submission-title' ).val();
    var excerpt = $( '#post-submission-excerpt' ).val();
    var content = $( '#post-submission-content' ).val();
    var status = 'draft';

    var data = {
        title: title,
        excerpt: excerpt,
        content: content
    };

    $.ajax({
        method: "POST",
        url: POST_SUBMITTER.root + 'wp/v2/posts',
        data: data,
        beforeSend: function ( xhr ) {
            //xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
        },
        success : function( response ) {
            console.log( response );
            alert( POST_SUBMITTER.success );
        },
        fail : function( response ) {
            console.log( response );
            alert( POST_SUBMITTER.failure );
        }

    });

});

下面是我如何初始化 javascript:

function holiday_scripts() {

    // Onload JS
    wp_enqueue_script( 'holiday-js', get_template_directory_uri() . '/js/holiday.js', array(), false, true );

    //localize data for script
    wp_localize_script( 'holiday-js', 'POST_SUBMITTER', array(
        'root' => esc_url_raw( rest_url() ),
        'nonce' => wp_create_nonce( 'wp_rest' ),
        'success' => __( 'Thanks for your submission!', 'your-text-domain' ),
        'failure' => __( 'Your submission could not be processed.', 'your-text-domain' ),
        'current_user_id' => 9
        )
     );
}
add_action( 'wp_enqueue_scripts', 'holiday_scripts' );

有人知道如何实现吗?

谢谢!

可通过三种不同的方式向 REST 进行身份验证 API:

  1. Cookie - 这就是你现在使用的
  2. OAuth - 前端需要 OAuth 插件和嵌入密钥
  3. Basic - 需要在前端嵌入 username/password

在此处查看有关使用这些方法的文档:http://v2.wp-api.org/guide/authentication/

在前端嵌入身份验证信息时存在明显的安全风险,这是 OAuthBasic 所要求的,因为任何人都可以作为与密钥关联的用户进行身份验证.我对 WP OAuth 插件不够熟悉,不知道您可以控制访问的粒度,但我认为您真的做不到。

最简单的解决方案是在 REST API 之外编写您自己的方法来处理这些更新(或为项目做出贡献以使未经身份验证的请求成为可能)。我在我的网站上为 Creating AJAX Functions 编写了一个指南,但基本上您想要将一个函数附加到 wp_ajax_nopriv_* 挂钩,其中 * 是您请求的“操作”参数。在你的钩子 PHP 函数中,你处理 post 插入并用 JSON 响应(你甚至可以匹配 WP REST API 格式)。

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
    });
}