создать пост wordpress.com используя остальные API

1

Я хочу, чтобы приложение php создало сообщение на wordpress.com, используя REST api.

Я использую этот код:

<?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 fromthe 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;

?>

но я получаю эту ошибку:

{"error": "unauthorized", "message": "Пользователь не может публиковать сообщения"}

Может мне помочь?

благодаря

  • 0
    в вашем определении client_secret отсутствует ' . И я надеюсь, что это не ваш настоящий секрет ...
  • 0
    я опечатка я редактировал .. есть идеи для этой ошибки?
Теги:
rest
wordpress-rest-api
wordpress.com

1 ответ

0

Стандартный способ создания сообщений - использовать файлы cookie и nonce.

Однако я нашел более простой способ сделать это.

  1. Установите плагин Basic-Auth в ваш Wordpress.

  2. Создайте пользователя Wordpress с именем admin и password admin (оба учетных данных небезопасны, используются только для демонстрационных целей)

  3. Создать пост с помощью кода:

    $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 {
        // ...
    }
    

Обратите внимание, что в примере выше версия 2 REST API используется.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню