I am using the REST API to create posts.
I am able to create normal posts, but I would like to create posts of custom type.
http://example.com/wp-json/wp/v2/posts
I am trying to POST
to the above URL with data as
title: 'Loreum Ipsum',
content: 'Test Post',
post_type: custom_type
which doesn’t create the post of type custom_type
instead normal post is created.
I tried posting to
http://example.com/wp-json/wp/v2/posts?post_type=custom_post
with the data,
title: 'Loreum Ipsum',
content: 'Test Post',
but still it creates normal post.
I also have tried to send the data as
title: 'Loreum Ipsum',
content: 'Test Post',
type: custom_type
to http://example.com/wp-json/wp/v2/posts
which also creates normal post.
I am using POSTMAN to send the data. What else should I try?
Any help or suggestions appreciated!
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();
});