[wp-trac] [WordPress Trac] #40697: Can't create new post by REST API but I can update existing post

WordPress Trac noreply at wordpress.org
Wed May 10 15:35:08 UTC 2017


#40697: Can't create new post by REST API but I can update existing post
--------------------------+-------------------------
 Reporter:  Alaa Rihan    |       Owner:
     Type:  defect (bug)  |      Status:  closed
 Priority:  normal        |   Milestone:
Component:  REST API      |     Version:  4.7.4
 Severity:  normal        |  Resolution:  worksforme
 Keywords:                |     Focuses:
--------------------------+-------------------------
Changes (by JPry):

 * status:  reopened => closed
 * resolution:   => worksforme


Comment:

 @Alaa Rihan The problem is your code.

 You need a `/` before `posts`, like this: `url: apiData.apiURL + '/posts'`

 I created a new site using WordPress 4.7.4 and used the same script
 localization you provided:

 {{{#!php
 <?php
         wp_localize_script( 'myapp', 'apiData', array(
                 'nonce' => wp_create_nonce( 'wp_rest' ),
                 'apiURL' => rest_url( 'wp/v2' ),
         ) );
 }}}

 I created very similar JS to post to the API:


 {{{#!js
 jQuery.ajax({
     method: "POST",
     url: apiData.apiURL + '/posts',
     data: {
         title: "Test from the api!",
         content: "This is my cool post content."
     },
     beforeSend: function (r) {
         r.setRequestHeader('X-WP-Nonce', apiData.nonce);
     }, success: function (r) {
         console.log(r);
     }, fail: function (r) {
         console.log(r);
     }
 });
 }}}

 I got a successful response and a new post created.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/40697#comment:5>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list