WordPress REST API-允许任何人发布 [英] WordPress REST API - Allow anyone to POST

查看:111
本文介绍了WordPress REST API-允许任何人发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building an application on WordPress that requires a simple front end form where anyone can submit information that needs to be saved in the database. I am attempting to handle this through the REST API. (Due to the nature of the application, there can not be any redirection of the page when this information is submitted.)

设置REST API(v2)没问题,这样我就可以提交帖子了.当我登录WordPress时,效果很好.当我未登录WordPress时尝试填写表格时,收到错误消息.

I have no problem setting up the REST API (v2) so that I can submit a post. It works great when I am logged into WordPress. When I try to fill out the form when I am not logged in to WordPress, I receive an error.

无法加载资源:服务器的响应状态为403(禁止)

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

如何设置API以从任何未经身份验证的人那里接收POST?

How can I set the API to receive a POST from anyone without authentication?

这是我的JavaScript:

Here is my 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的方式:

Here is how I am initializing my 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' );

有人对如何做到这一点有任何想法吗?

Does anyone have any idea on how to accomplish this?

谢谢!

推荐答案

有三种不同的方法可以对REST API进行身份验证:

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

  1. Cookie-这就是您现在正在使用的
  2. OAuth-在前端需要OAuth插件和嵌入密钥
  3. Basic-需要在前端嵌入用户名/密码
  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

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

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

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

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.

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

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

这篇关于WordPress REST API-允许任何人发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆