phpjsonwordpressapiwordpress-json-api

How to interact with the Wordpress JSON API using PhP?


I'm trying to create a PhP script that will automatically post an article on my wordpress website (I'm using the wordpress CMS, it's not a wordpress.com website).

Here is what I've done so far:

Plugin installations

I've installed and activated the WordPress JSON API and the Basic Auth plugins on my website.

Library and code

I've downloaded the WP REST php Library and I've uploaded the files in src in the same folder as my script.

Here is the code of my php script:

require_once( 'class-wp-rest-client.php' );
require_once( 'class-wp-rest-request.php' );
require_once( 'class-wp-rest-exception.php' );
require_once( 'class-wp-rest-transport.php' );
require_once( 'class-wp-rest-transport-curl.php' );
require_once( 'class-wp-rest-transport-wp-http-api.php' );
require_once( 'class-wp-rest-object.php' );
require_once( 'class-wpapi-rest-object-post.php' );
require_once( 'class-wpapi-rest-object-posts.php' );
require_once( 'class-wpapi-rest-client.php' );


use WP_REST_Client;
use WP_REST_Request;
use WP_REST_Object;
use WP_REST_Exception;
use WP_REST_Transport;
use WP_REST_Transport_WP_HTTP_API;
use WP_REST_Transport_Curl;
use WPAPI_REST_Object_Post;
use WPAPI_REST_Object_Posts;
use WPAPI_REST_Basic_Auth_Client;


$post_data=array(
            'title' => 'New Post',
            'content_raw' => 'This is a test'
        );



$wp_api_client = new WPAPI_REST_Basic_Auth_Client( 'http://example.com', 'login', 'password' );

if ($wp_api_client) echo "connected";

try {

$current_post = WPAPI_REST_Object_Post::initWithId( 1, $wp_api_client );
$current_post_data = $current_post->get();
echo 'Post Title:' . $current_post_data->ID;    

} catch ( WP_REST_Exception $e ) { print_r($e); }

?>

And I'm getting this error:

WP_REST_Exception Object ( [message:protected] => HTTP error for request; response:

I'm not sure if the error is coming from me not using the library properly or else. Anyone can help me with this?

Thanks a lot guys!


Solution

  • For those having the same issue, it seems that it is the Basic Auth plugin that is not working.

    For a better working API, connect your site with JetPack to Wordpress.com and use their API.

    Cheers, Arthur