How to create post using wordpress rest api without authentication ?


First you need to create a custom rest api end point

Code (functions.php)


add_action( 'rest_api_init', function () {
 register_rest_route( 'myplugin/v1', '/post/(?P<title>\d+)', array(
  'methods' => 'GET',
  'callback' => 'create_ui_post',
 ) );
});

Callback function


function create_ui_post( $data ) {
 
}

Check the parameter is empty or not if empty return error message

if( isset( $data['title'] ) && isset( $data['content'] ) )
{
 
}
else 
{
 return new WP_Error( 'invalid_arguments', 'Invalid Request', array( 'status' => 404 ) );
}

Create the post

$post = array();
$post['post_status']   = 'publish';
$post['post_type']     = 'post';
$post['post_title']    = $data['title'];
$post['post_author']    = '1';
$post['post_content']  = $data['content']; 
$post_id = wp_insert_post( $post ); 
return $post_id;

Final Code


// Functions.php
function create_ui_post( $data ) {
 global $woocommerce;
 $posts = get_posts( array(
  'title' => $data['title'],
 ) );
 if( isset( $data['title'] ) && isset( $data['content'] ) )
 {
  $post = array();
  $post['post_status']   = 'publish';
  $post['post_type']     = 'post';
 $post['post_author']    = '1';
  $post['post_title']    = $data['title'];
  $post['post_content']  = $data['content']; 
  $post_id = wp_insert_post( $post ); 
  return $post_id;
 }
 else {
  return new WP_Error( 'invalid_arguments', 'Invalid Request', array( 'status' => 404 ) );
 } 
 
} 
add_action( 'rest_api_init', function () {
 register_rest_route( 'myplugin/v1', '/post/(?P<title>\d+)', array(
  'methods' => 'GET',
  'callback' => 'create_ui_post',
 ) );
});

Usage 

/wp-json/myplugin/v1/post/1?title=[your_title]&content=[your_content]

[your_title] - title of the post without []
[your_content] - body of the post without []




Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.