WordPress REST API-允许任何人进行POST


WordPress REST API - Allow anyone to POST

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

我设置REST API(v2)没有问题,这样我就可以提交一篇文章了。当我登录WordPress时,它工作得很好。当我没有登录WordPress时尝试填写表格时,我收到一个错误。

加载资源失败:服务器响应状态为403(禁止)

如何设置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-要求在前端嵌入用户名/密码

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

在前端嵌入身份验证信息时存在明显的安全风险,这是OAuthBasic所要求的,因为任何人都可以作为密钥关联的用户进行身份验证。我对WPOAuth插件还不够熟悉,不知道你可以在多大程度上控制访问,但我认为你真的不能。

最简单的解决方案是在REST API之外编写自己的方法来处理这些更新(或者为项目做出贡献,使未经验证的请求成为可能)。我在我的网站上写了一个创建AJAX函数的指南,但基本上你想把一个函数附加到wp_ajax_nopriv_*钩子上,其中*是";动作";参数。在挂钩的PHP函数中,您可以处理插入后并使用JSON进行响应(甚至可以匹配WPRESTneneneba 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
    });
}