Wordpress教程(一) Rest Api简单入门

Wordpress是当今最强大的博客+cms系统,最近在用wordpress给客户搭建一款小程序,涉及到Rest Api,于是有了本篇,本篇根据官方文档和个人的理解编写,如有错误或者疏漏,请同学指正

全局参数

通过全局参数的设置,能够使接口具备一些GraphQl的能力

_fields

作用:过滤字段
使用形式:
/wp/v2/posts?_fields=author,id,excerpt,title,link
或者
/wp/v2/posts?_fields[]=author&_fields[]=id&_fields[]=excerpt&_fields[]=title&_fields[]=link
另外,支持嵌套
?_fields=article.author,article.cat.cat_name
表示返回访问文章的作者和文章的分类的分类名

_embed

作用:大多数资源包括相关资源的链接。例如,一个帖子可以链接到父帖子,或者链接到帖子的评论。为了减少HTTP请求的数量,客户可能希望获取一个资源以及链接的资源。_embed参数向服务器表明,响应应该包括这些嵌入资源。
用法:/wp/v2/posts?_embed=author,wp:term
表示表示除了读取文章外,还嵌入作者和相关连接

_method

和大部分rest规范一些,用来表示请求方式,wordpress支持参数的形式,当然,wordpress也支持附加在header的形式
使用

POST /wp-json/wp/v2/posts/42 HTTP/1.1
Host: example.com
X-HTTP-Method-Override: DELETE

_envelope

调试模式:与_method类似,一些服务器、客户端和代理不支持访问完整的响应数据。该API支持传递一个_envelope参数,调试模式下请求将返回更详细的信息,包括头文件和状态码

    "status": 200,
    "headers": {
        "Allow": "GET"
    }

_jsonp

使API原生支持JSONP响应,允许传统浏览器和客户端的跨域请求。这个参数需要一个JavaScript回调函数,它将被预置到数据中。然后这个URL可以通过

page,per_page,offset

对于一些接口,用来表示分页

order,orderby

用来排序

Authentication认证

X-WP-Nonce

这种认证方法依赖于WordPress cookies。因此,这种方法只适用于在WordPress内部使用REST API并且当前用户已经登录的情况下。此外,当前用户必须有适当的能力来执行正在进行的操作,老俊理解为这里的nonce相当于我们开发表单提交时常会在表单里面置入token一样
如何使用?
先利用wp_create_nonce函数生成nonce,

<?php
wp_localize_script( 'wp-api', 'wpApiSettings', array(
    'root' => esc_url_raw( rest_url() ),
    'nonce' => wp_create_nonce( 'wp_rest' )
) );

再放入X-WP-Nonce

options.beforeSend = function(xhr) {
    xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);

    if (beforeSend) {
        return beforeSend.apply(this, arguments);
    }
};

Basic Authentication

Basic Authentication方式使用了后台的应用程序密码,在后台用户管理那边可以设置。
使用

curl --user "USERNAME:PASSWORD" https://HOSTNAME/wp-json/wp/v2/users?context=edit

然而curl --user其实使用的就是Basic Auth,

This will make curl use the default “Basic” HTTP authentication method. Yes, it is actually called Basic and it is truly basic. To explicitly ask for the basic method, use --basic.
The Basic authentication method sends the user name and password in clear text over the network (base64 encoded) and should be avoided for HTTP transport.
这将使curl使用默认的 "Basic "HTTP认证方法。是的,它实际上被称为Basic,而且是真正的基本。要明确要求使用Basic方法,请使用–basic。
Basic认证方法在网络上以明文形式发送用户名和密码(base64编码),应该避免用于HTTP传输。

通过Curl来使用

<?php
$username = 'admin';
$application_password = 'MGOw EG9V 04xo sUZ0 60wo J2OG';
 
$url = 'SITE_URL/wp-json/wp/v2/posts';
  
$json = json_encode([
    'title' => 'Post using REST API',
    'content' => 'Post content using REST API',
    'status' => 'publish',
]);
 
try {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$application_password);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    $result = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    print_r(json_decode($result));
} catch(Exception $e) {
    echo $e->getMessage();
}

通过Guzzle来使用

<?php
require_once "vendor/autoload.php";
  
use GuzzleHttp\Client;
 
$username = 'admin';
$application_password = 'MGOw EG9V 04xo sUZ0 60wo J2OG';
 
try {
    $client = new Client([
        // Base URI is used with relative requests
        'base_uri' => 'SITE_URL',
    ]);
     
    $response = $client->request('POST', '/wp-json/wp/v2/posts', [
        'json' => [
            'title' => 'Post using REST API',
            'content' => 'Post content using REST API',
            'status' => 'publish',
        ],
        "headers" => [
            "Authorization" => "Basic ". base64_encode($username.':'.$application_password)
        ],
    ]);
 
    $body = $response->getBody();
    $arr_body = json_decode($body);
    print_r($arr_body);
} catch(Exception $e) {
    echo $e->getMessage();
}

通过Wordpress插件来实现

可以使用JWT Authentication for WP REST API这款插件来实现jwt token认证,也可以搜索别的插件,wordpress社区提供了非常多的插件

客户端库的使用

1、在wordpress内部注册wp-api脚本

wp_enqueue_script( 'wp-api' );
//或
wp_enqueue_script( 'my_script', 'path/to/my/script', array( 'wp-api' ) );

脚本路径wp-includes/js/wp-api.js,脚本基于backbone.js
使用方法

// Create a new post
var post = new wp.api.models.Post( { title: 'This is a test post' } );
post.save();

// Load an existing post
var post = new wp.api.models.Post( { id: 1 } );
post.fetch();

2、node-wpapi

可以用于node.js端和javascript客户端
安装和使用

npm install --save wpapi
var WPAPI = require( 'wpapi' );
var wp = new WPAPI({ endpoint: 'http://src.wordpress-develop.dev/wp-json' });
// Callbacks
wp.posts().get(function( err, data ) {
    if ( err ) {
        // handle err
    }
    // do something with the returned posts
});

// Promises
wp.posts().then(function( data ) {
    // do something with the returned posts
}).catch(function( err ) {
    // handle error
});

常用的Rest Api

根网址:https:/域名/wp-json。

资源路由
块类型相关/wp/v2/block-types
文章分类相关/wp/v2/categories
文章评论相关/wp/v2/comments
媒体文件相关/wp/v2/media
文章列表相关/wp/v2/pages
文章内容相关/wp/v2/posts
标签/wp/v2/tags
用户/wp/v2/users

具体查看:https://developer.wordpress.org/rest-api/reference/

如何扩展Rest Api

修改已有api的响应

使用register_rest_field 或者register_meta ,注册到rest_api_init钩子上
以下举例给comment添加一个myphone字段和mymeta元字段

add_action( 'rest_api_init', function () {
    register_rest_field( 'comment', 'myphone', array(
        'get_callback' => function( $comment_arr ) {
            $comment_obj = get_comment( $comment_arr['id'] );
            return (string) $comment_obj->myphone;
        },
        'update_callback' => function( $myphone, $comment_obj ) {
            $ret = wp_update_comment( array(
                'comment_ID'    => $comment_obj->comment_ID,
                'myphone' => $myphone
            ) );
            if ( false === $ret ) {
                return new WP_Error(
                  'rest_comment_karma_failed',
                  __( 'Failed to update comment karma.' ),
                  array( 'status' => 500 )
                );
            }
            return true;
        },
        'schema' => array(
            'description' => '我的电话',
            'type'        => 'text'
        ),
    ) );
} );

添加新的api

使用register_rest_route函数,可以添加api路由,register_rest_route必须放置在rest_api_init 钩子中,register_rest_route的定义如下:

register_rest_route( string $namespace, string $route, array $args = array(), bool $override = false ): bool

函数接收4个参数, n a m e s p a c e 表示路由空间, namespace表示路由空间, namespace表示路由空间,route为路由路径,如果 n a m e s p a c e = ′ l a o j u n / v 1 ′ , namespace='laojun/v1', namespace=laojun/v1,route=‘route’,那么完整的api地址就是http://域名/wp-json/laojun/v1/route
$arg参数是一个数组,比较复杂,api的请求方法、路由回调、路由验证,路由权限等功能都定义在这里。如

        add_action( 'rest_api_init', function() {
            register_rest_route( 'laojun/v1', '/route/', array(
                'methods' => 'POST',
                'callback' =>  'plugin_name_route_api',
                'args' => array(
                  'id' => array(
                    'validate_callback' => function($param, $request, $key) {
                    return is_numeric( $param );
                    }
                  ),
                ),              
                'permission_callback' => function() { return ''; }
            ) );
        } );

这里定义了请求方法为Post,路由回调plugin_name_route_api表示请求这个路由时会执行plugin_name_route_api这个方法。validate_callback表示在请求前会验证请求参数id是否为数字,permission_callback表示请求权限验证。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值