使用rest api创建post wordpress.com

问题描述 投票:0回答:3

我想制作 php 应用程序使用 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":"未经授权","message":"用户无法发布帖子"}

可以帮助我吗?

谢谢

php rest api wordpress-rest-api wordpress.com
3个回答
8
投票

创建帖子的标准方法是使用 cookies 和随机数。

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

  1. Basic-Auth 插件安装到您的 WordPress。

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

请注意,上面的示例中使用了 REST API 版本 2。


2
投票

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

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

wordpress.com 提供了 oAuth 支持进行身份验证。


最近我创建了一篇帖子,演示如何使用 oAuth 在 wordpress.com 上创建帖子。您可以阅读该文章:使用 oAuth 和 Rest API 在 wordpress.com 网站上创建帖子

以下是在 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 );
}

0
投票

如果有人在使用带有应用程序密码的 REST API 时收到 401 未经授权的错误,请确保您使用 WordPress 用户名(而不是应用程序密码名称) 和应用程序密码

{"code":"rest_cannot_manage_templates","message":"Sorry, you are not allowed to access the templates on this site.","data":{"status":401}}
© www.soinside.com 2019 - 2024. All rights reserved.