使用rest api创建post wordpress.com

时间:2016-03-03 07:14:33

标签: php rest api wordpress-rest-api wordpress.com

我想让php app使用REST api在wordpress.com上创建帖子。

我使用此代码:

<?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”:“未授权”,“消息”:“用户无法发布帖子”}

可以帮帮我吗?

由于

2 个答案:

答案 0 :(得分:0)

创建帖子的标准方法是使用cookies和nonce。

但是我找到了一种更简单的方法。

  1. 在您的wordpress中安装Basic-Auth插件。

  2. 使用用户名admin和密码admin创建wordpress用户(两个凭据都不安全,仅用于演示目的)

  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 {
        // ...
    }
    
  4. 请注意,在上面的示例中,使用了REST API的第2版。

答案 1 :(得分:0)

答案是正确的,我们可以使用“Basic-Auth”插件来发出 Rest API 请求。

但是,@vallez 想在 wordpress.com 网站上创建一个帖子。

并且 wordpress.com 为身份验证提供 oAuth 支持。


最近我创建了一个帖子,演示了如何使用 oAuth 在 wordpress.com 上创建帖子。您可以在 create the post on wordpress.com site using oAuth and Rest API

阅读这篇文章

以下是在 wordpress.com 上使用 oAuth 成功创建帖子的步骤。

第 1 步:添加身份验证详细信息以获取身份验证密钥。

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

下面是返回访问密钥的函数 get_access_key()。

第 2 步:获取访问密钥。

/**
 * 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;
}

第 3 步: 设置帖子参数并传递它以创建帖子。

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

第 4 步:使用访问密钥创建帖子。

现在,我们有了访问密钥和创建帖子参数。因此,让我们将它们传递给函数 create_post()。

create_post( $access_key, $post_args );

第 5 步:使用访问密钥创建帖子。

/**
 * 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 );
}