WordPress REST API how to post

How to use WordPress REST API to post article? I can edit post using the following PHP code, i’m using the Basic Authentication.

require( dirname(__FILE__) . '/wp-load.php' );

$headers = array (
    'Authorization' => 'Basic ' . base64_encode( 'username' . ':' . 'password' ),
);

// Edit post
$url = rest_url( 'wp/v2/posts/1' );

$data = array(
    'title' => 'Test API Edit' 
);

$response = wp_remote_post( $url, array (
    'method'  => 'POST',
    'headers' => $headers,
    'body'    =>  $data
) );

print_r($response);

But I can not post new article

Read More
<?php

require( dirname(__FILE__) . '/wp-load.php' );

$headers = array (
    'Authorization' => 'Basic ' . base64_encode( 'username' . ':' . 'password' ),
);

// post new article

$url = rest_url( 'wp/v2/create_post/' );

$data = array(
    'title' => 'Post from API',
    'content' => 'test contents'

);

$response = wp_remote_post( $url, array (
    'method'  => 'POST',
    'headers' => $headers,
    'body'    =>  $data
) );

print_r($response);

The return is always No route was found matching the URL and request method

Any suggestions?

Related posts

1 comment

  1. It looks like you are using the wrong endpoint for POSTing to the REST API. As mentioned here the endpoint for creating new posts is:

    /wp/v2/posts

    Hope this solves your problem!

Comments are closed.