WordPress REST Create Post of Custom Type

Make sure your post type is shown in the REST API.

$args = array(
  //* Use whatever other args you want
  'show_in_rest'          => true,
  'rest_base'             => 'myslug',
  'rest_controller_class' => 'WP_REST_Posts_Controller',
);
register_post_type( 'myslug', $args );

The endpoint to create a post would then be http://example.com/wp-json/wp/v2/myslug.

Edit:

The above is all that’s needed for a custom post type to be available as a REST endpoint using the default WP_REST_Posts_Controller. I initially had the following code, because I think it makes using the REST API easier. However, as pointed out in the comments, it’s not needed to answer this question. You can just use the endpoint.

function wpse294085_wp_enqueue_scripts() {
  wp_enqueue_script( 'wp-api' );
  wp_enqueue_script( 'my-script', PATH_TO . 'my-script.js', [ 'wp-api' ] );
}
add_action( 'wp_enqueue_scripts', 'wpse294085_wp_enqueue_scripts' );

Then in my-script.js, just use Backbone.

wp.api.loadPromise.done( function() {
  var post = new wp.api.models.Myslug( {
    'id': null,
    'title': 'Example New Post',
    'content': 'YOLO'
  } );
  var xhr = post.save();
});

Leave a Comment