Create post wordpress.com using rest API
Asked Answered
N

3

5

I want to make PHP app to create post on wordpress.com using REST API.

I use this code:

<?php

$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, array(
'client_id' => 12345,
'redirect_uri' => 'http://example.com/wp/test.php',
'client_secret' => 'L8RvNFqyzvqh25P726jl0XxSLGBOlVWDaxxxxxcxxxxxxx',
'code' => $_GET['code'], // The code from the previous request
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);

$auth = curl_exec( $curl );
$secret = json_decode($auth);
$access_token = $secret->access_token;


$post = array(
'title'=>'Hello World',
'content'=>'Hello. I am a test post. I was created by
the API',
'date'=>date('YmdHis'),
'categories'=>'API','tags=tests'
);
$post = http_build_query($post);
$apicall = "https://public-api.wordpress.com/rest/v1/sites/mysite.wordpress.com/posts/new";
$ch = curl_init($apicall);
curl_setopt($ch, CURLOPT_HTTPHEADER, array
('authorization: Bearer ' . $access_token,"Content-Type: application/x-www-form-urlencoded;
charset=utf-8"));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_VERBOSE, 1); 
$return = curl_exec($ch);
echo "<pre>";
print_r($return);
exit;

?>

but I get this error:

{"error":"unauthorized","message":"User cannot publish posts"}

Can help me?

Nay answered 3/3, 2016 at 7:14 Comment(2)
your client_secret definition is missing a '. And I hope this is not your real secret ...Egypt
i mistyped. i edited.. any idea for this error?Nay
C
8

Standard way to create posts is to use cookies and nonce.

However I found a more easy way to do it.

  1. Install Basic-Auth plugin to your wordpress.

  2. Create wordpress user with username admin and password admin (both credentials are insecure, used for demonstration purposes only)

  3. Create post using code:

    $username = 'admin';
    $password = 'admin';
    $rest_api_url = "http://my-wordpress-site.com/wp-json/wp/v2/posts";
    
    $data_string = json_encode([
        'title'    => 'My title',
        'content'  => 'My content',
        'status'   => 'publish',
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $rest_api_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string),
        'Authorization: Basic ' . base64_encode($username . ':' . $password),
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $result = curl_exec($ch);
    
    curl_close($ch);
    
    if ($result) {
        // ...
    } else {
        // ...
    }
    

Note that in example above version 2 of REST API is used.

Cryptocrystalline answered 20/2, 2018 at 21:17 Comment(1)
i dont think it can be done at wordpress.com.Ulibarri
M
2

The answer is right that we can use the "Basic-Auth" plugin to make a Rest API request.

But, @vallez want to create a post on wordpress.com website.

And wordpress.com provide the oAuth support for authentication.


Recently I have created a post which demostrate about using the oAuth to create a post on wordpress.com. You can read the article at create the post on wordpress.com site using oAuth and Rest API

Below are the steps to successfully create a post with oAuth on wordpress.com.

Step 1: Add authentication details to get auth key.

$auth_args = array(
    'username'      => '',
    'password'      => '',
    'client_id'     => '',
    'client_secret' => '',
    'grant_type'    => 'password', // Keep this as it is.
);
$access_key = get_access_key( $auth_args );

Below is the function get_access_key() which return the access key.

Step 2: Get Access Key.

/**
 * Get Access Key.
 * 
 * @param  array $args  Auth arguments.
 * @return mixed        Auth response.
 */
function get_access_key( $args ) {

    // Access Token.
    $curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
    curl_setopt( $curl, CURLOPT_POST, true );
    curl_setopt( $curl, CURLOPT_POSTFIELDS, $args );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
    $auth = curl_exec( $curl );
    $auth = json_decode($auth);

    // Access Key.
    return $auth->access_token;
}

Step 3: Set post arguments and pass it create the post.

$post_args = array(
    'title'       => 'Test Post with oAuth',
    'content'     => 'Test post content goes here..',
    'tags'        => 'tests',
    'post_status' => 'draft',
    'categories'  => 'API',
);

Step 4: Create a post with the access key.

Now, We have access key and the create post arguments. So, Lets pass them to function create_post().

create_post( $access_key, $post_args );

Step 5: Create a post with access key.

/**
 * Create post with access key.
 * 
 * @param  string $access_key   Access key.
 * @param  array $post_args     Post arguments.
 * @return mixed                Post response.
 */
function create_post( $access_key, $post_args )
{
    $options  = array (
        'http' => array(
            'ignore_errors' => true,
            'method'        => 'POST',
            'header'        => array(
                0 => 'authorization: Bearer ' . $access_key,
                1 => 'Content-Type: application/x-www-form-urlencoded',
            ),
            'content' => http_build_query( $post_args ),
        ),
    );
     
    $context  = stream_context_create( $options );
    $response = file_get_contents(
        'https://public-api.wordpress.com/rest/v1/sites/YOURSITEID/posts/new/',
        false,
        $context
    );
    return json_decode( $response );
}
Middlebrooks answered 22/12, 2020 at 5:42 Comment(1)
throwing error :{"code":"rest_invalid_param","message":"Invalid parameter(s): tags","data":{"status":400,"params":{"tags":"tags[0] is not of type integer."}}}Louden
K
0

Incase, someone is getting 401 Unauthorized error when using REST API with application password, make sure that you use WordPress username (not Application Password Name) and Application Password

{"code":"rest_cannot_manage_templates","message":"Sorry, you are not allowed to access the templates on this site.","data":{"status":401}}
Kauffman answered 8/5 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.