添加 WordPress REST API 自定义路由

文章2020-08-261,256 人已阅来源:水秋玄

由于 WordPress REST API 没有提供获取网站基本信息的api,所以需要在主题的 functions.php 添加自定义路由。

官方文档:https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

//自定义路由,返回网站基本信息
function api_get_info() {
	$data = array(//自定义要返回的数据
		"name" => get_bloginfo("name"),
		"description" => get_bloginfo("description"),
		"url" => get_bloginfo("url"),
		"admin_email" => get_bloginfo("admin_email")
	);
	if ( empty( $data ) ) {
		return null;
	}
	return $data;
}
add_action( 'rest_api_init', function () {
	register_rest_route( 'wp/v2', '/info', array(
		'methods' => 'GET',
		'callback' => 'api_get_info',
	) );
} );

自定义后api地址为:http://网站地址(或wordpress安装路径)/wp-json/wp/v2/info

{//api返回结果
  "name": "水秋玄",
  "description": "我的收藏小站",
  "url": "http:\/\/im.mkinit.com",
  "admin_email": "im@mkinit.com"
}