WordPress Rest API 速查

内置接口

/wp/v2/posts

post 列表接口

官方文档: https://developer.wordpress.org/rest-api/reference/posts/

举例: http://localhost/wp/wp-json/wp/v2/posts?per_page=2&page=2&include=2063,2068,874,1799,2047,2050,2052,2042,2039,2087

/wp/v2/pages

page 列表接口

https://developer.wordpress.org/rest-api/reference/posts/

/wp/v2/categories

category 列表接口

/wp/v2/tags

tag 列表接口

/wp/v2/users

user 列表接口

官方文档: https://developer.wordpress.org/rest-api/reference/users/

/wp/v2/users/me

获取当前登录用户的 userinfo,需要授权

{
  "id": 1,
  "name": "Arvin",
  "url": "",
  "description": "",
  "link": "http://localhost/wp/company/arvin",
  "slug": "arvin",
  "meta": [],
  "_links": {
    "self": [
      {
        "href": "http://localhost/wp/wp-json/wp/v2/users/1"
      }
    ],
    "collection": [
      {
        "href": "http://localhost/wp/wp-json/wp/v2/users"
      }
    ]
  }
}

/wp/v2/comments

评论列表接口

/wp/v2/search

整站搜索接口,区分于单独 post_type 的 search

整站搜索 lorem 的例子: /wp/v2/search?search=lorem&per_page=5&page=1

官方文档: https://developer.wordpress.org/rest-api/reference/search-results/

/wp/v2/settings

网站设置接口,一般只有需要开发管理员 APP 才需要用到。

官方文档: https://developer.wordpress.org/rest-api/reference/settings/

/wp/v2/themes

获取主题信息,一般只有需要开发管理员 APP 才需要用到。

官方文档: https://developer.wordpress.org/rest-api/reference/themes/

/wp/v2/plugins

获取主题信息,一般只有需要开发管理员 APP 才需要用到。

官方文档: https://developer.wordpress.org/rest-api/reference/plugins/

/wp/v2/sidebars

建站服务平台可能会用到

/wp/v2/widgets

建站服务平台可能会用到

自定义字段

默认的 rest api 不会返回 custom field,需要自行将自定义字段加到 rest api。

方法一

通过register_rest_fields将自定义字段加到 rest api

add_action( 'rest_api_init', 'add_custom_fields' );
function add_custom_fields() {
    register_rest_field(
    'post',
    'custom_fields', // New Field Name in JSON RESPONSEs
    array(
        'get_callback'    => 'get_custom_fields', // custom function name
        'update_callback' => null,
        'schema'          => null,
        )
    );
}

function get_custom_fields( $object, $field_name, $request ) {
    //your code goes here
    return $customfieldvalue;
}

方法二

通过rest_prepare_post将自定义字段加到 rest api

function my_rest_prepare_post( $data, $post, $request ) {
  $_data = $data->data;
  $_data[$field] = get_post_meta( $post->ID, 'my_custom_field_key', true );
  $data->data = $_data;
  return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );

或者一次性添加多个自定义字段

function my_rest_prepare_post( $data, $post, $request ) {
  $_data = $data->data;
  // My custom fields that I want to include in the WP API v2 responce
  $fields = ['writer', 'publisher', 'year', 'youtube_link'];

  foreach ( $fields as $field ) {
    $_data[$field] = get_post_meta( $post->ID, $field, true );
  }

  $data->data = $_data;
  return $data;
}

add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
© 2022  Arvin Xiang
Built with ❤️ by myself