skip to Main Content

I started creating an ajax post form that takes name and email as inputs. The idea is to have the anonymous, un-logged user to fill out the fields, and when the forms posting succeeds on the API, the user gets access to download an eBook.

The admin wants to be able to view the data of all the users that have filled out the form on the backend, so what I did is create a new custom post type labeled "ebook-user".

From the researching that I’ve done online, it seems that a user could only post on post comments to the rest api. Is there a way to enable anonymous posting on a custom post type?

Right now, when I post with my current code, I get a 401 error:

{
"code": "rest_cannot_create",
"message": "Sorry, you are not allowed to create posts as this user.",
"data": {
"status": 401
}
}

Here’s my js code:

fetch(`${site_url}/wp-json/wp/v2/ebook-user`, {
        credentials: 'same-origin',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': ajax_nonce,
        },
        body: JSON.stringify(credentials)
      })

      .then((res) => res.json())
      .then((res) => { 
        console.log(res)
        if(res.data.status == 403) {
          formMsg.textContent = `Error`
        }
        console.log('success');
      })
      .catch((err) => {
        console.error(err);
      })

Note that I did add this line in my functions.php, which enables comment posting as guest user

add_filter( ‘rest_allow_anonymous_comments’, ‘__return_true’ );

2

Answers


  1. Since you want to POST with an un-authenticated user, I’d create a custom endpoint to do it.

    Something like:

    /wp-json/mytld/v1/ebook

    Allow POST to the end point but nothing else.

    Validate the input VERY CAREFULLY and I’d go so far as to do things like make sure you don’t already know the email address before allowing the post to succeed.

    This requires a little more code but gives you a lot more control.

    =C=

    Login or Signup to reply.
  2. add_action( 'rest_api_init', function () {
      register_rest_route( 'getdata/v1', '/author/(?id)', array(
        'methods' => 'GET',
        'callback' => 'my_bookdata_func',
      ) );
    } );
    
    function my_bookdata_func( $data ) {
      $posts = get_posts( array(
        'author' => $data['id'],
      ) );
     
      if ( empty( $posts ) ) {
        return null;
      }
     
      return $posts[0]->post_title;
    }
    
    
    Url to access
    wp-json/getdata/v1/author/(?id).
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search