[API] Adding REST API Support For Custom Content Types

API REST có thể tạo các tuyến cho các loại bài đăng tùy chỉnh và các đơn vị phân loại tùy chỉnh bên trong không gian tên wp / v2, sử dụng cùng một bộ điều khiển như bộ điều khiển loại bài đăng mặc định hoặc bộ điều khiển thuật ngữ phân loại. Ngoài ra, bạn có thể sử dụng bộ điều khiển và không gian tên của riêng mình. Tài liệu này sẽ đề cập đến việc sử dụng bộ điều khiển mặc định cho các tuyến API của loại nội dung tùy chỉnh của bạn. Đây là cách dễ nhất và đảm bảo khả năng tương thích cao nhất với các bên thứ ba.

Registering A Custom Post Type With REST API Support #

Khi đăng ký một loại bài đăng tùy chỉnh, nếu bạn muốn nó có sẵn thông qua API REST, bạn nên đặt 'show_in_rest' => true trong các đối số được truyền cho register_post_type. Đặt đối số này thành true sẽ thêm một tuyến đường trong không gian tên wp / v2.

/**
 * Register a book post type, with REST API support
 *
 * Based on example at: https://codex.wordpress.org/Function_Reference/register_post_type
 */
add_action( 'init', 'my_book_cpt' );
function my_book_cpt() {
$args = array(
  'public'       => true,
  'show_in_rest' => true,
  'label'        => 'Books'
);
register_post_type( 'book', $args );

Bạn có thể tùy chọn đặt đối số rest_base để thay đổi url cơ sở, nếu không, url này sẽ được mặc định thành tên của loại bài đăng. Trong ví dụ dưới đây, “sách” được sử dụng làm giá trị của rest_base. Điều này sẽ tạo URL cho tuyến đường wp-json / wp / v2 / books thay vì wp-json / wp / v2 / book /, vốn sẽ là mặc định.

Ngoài ra, bạn có thể truyền một đối số cho rest_controller_class. Lớp này phải là một lớp con của WP_REST_Controller. Theo mặc định, WP_REST_Posts_Controller được sử dụng làm bộ điều khiển. Nếu bạn đang sử dụng bộ điều khiển tùy chỉnh, thì bạn có thể sẽ không ở trong không gian tên wp / v2.

Dưới đây là một ví dụ về đăng ký một loại bài đăng, có nhãn đầy đủ, hỗ trợ API REST, rest_base tùy chỉnh và đăng ký rõ ràng của bộ điều khiển mặc định:

Nếu bạn đang sử dụng rest_controller_class tùy chỉnh, thì REST API không thể tự động xác định tuyến đường cho một bài đăng nhất định. Trong trường hợp này, bạn có thể sử dụng bộ lọc rest_route_for_post để cung cấp thông tin này. Điều này cho phép loại bài đăng tùy chỉnh của bạn được định dạng đúng trong điểm cuối Tìm kiếm và cho phép các liên kết khám phá tự động.

<?php
/**
 * Register a book post type, with REST API support
 *
 * Based on example at: https://codex.wordpress.org/Function_Reference/register_post_type
 */
/**
 * Register a book post type, with REST API support
 *
 * Based on example at: https://codex.wordpress.org/Function_Reference/register_post_type
 */
add_action( 'init', 'my_book_cpt' );
function my_book_cpt() {
  $labels = array(
    'name'               => _x( 'Books', 'post type general name', 'your-plugin-textdomain' ),
    'singular_name'      => _x( 'Book', 'post type singular name', 'your-plugin-textdomain' ),
    'menu_name'          => _x( 'Books', 'admin menu', 'your-plugin-textdomain' ),
    'name_admin_bar'     => _x( 'Book', 'add new on admin bar', 'your-plugin-textdomain' ),
    'add_new'            => _x( 'Add New', 'book', 'your-plugin-textdomain' ),
    'add_new_item'       => __( 'Add New Book', 'your-plugin-textdomain' ),
    'new_item'           => __( 'New Book', 'your-plugin-textdomain' ),
    'edit_item'          => __( 'Edit Book', 'your-plugin-textdomain' ),
    'view_item'          => __( 'View Book', 'your-plugin-textdomain' ),
    'all_items'          => __( 'All Books', 'your-plugin-textdomain' ),
    'search_items'       => __( 'Search Books', 'your-plugin-textdomain' ),
    'parent_item_colon'  => __( 'Parent Books:', 'your-plugin-textdomain' ),
    'not_found'          => __( 'No books found.', 'your-plugin-textdomain' ),
    'not_found_in_trash' => __( 'No books found in Trash.', 'your-plugin-textdomain' )
  );
  $args = array(
    'labels'             => $labels,
    'description'        => __( 'Description.', 'your-plugin-textdomain' ),
    'public'             => true,
    'publicly_queryable' => true,
    'show_ui'            => true,
    'show_in_menu'       => true,
    'query_var'          => true,
    'rewrite'            => array( 'slug' => 'book' ),
    'capability_type'    => 'post',
    'has_archive'        => true,
    'hierarchical'       => false,
    'menu_position'      => null,
    'show_in_rest'       => true,
    'rest_base'          => 'book',
    'rest_controller_class' => 'WP_REST_Posts_Controller',
    'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
  );
  register_post_type( 'book', $args );
}
function my_plugin_rest_route_for_post( $route, $post ) {
    if ( $post->post_type === 'book' ) {
        $route = '/wp/v2/book/' . $post->ID;
    }
    return $route;
}
add_filter( 'rest_route_for_post', 'my_plugin_rest_route_for_post', 10, 2 );
?>

Registering A Custom Taxonomy With REST API Support

Đăng ký phân loại tùy chỉnh với hỗ trợ API REST rất giống với đăng ký loại bài đăng tùy chỉnh: pass 'show_in_rest' => true trong các đối số được chuyển đến register_taxonomy. Bạn có thể tùy ý chuyển rest_base để thay đổi url cơ sở cho các tuyến của đơn vị phân loại.

The default controller for taxonomies is WP_REST_Terms_Controller. You may modify this with the rest_controller_class if you choose to use a custom controller.

Here is an example of how to register a custom taxonomy with REST API support:

Nếu bạn đang sử dụng rest_controller_class tùy chỉnh, thì REST API không thể tự động xác định tuyến đường cho một cụm từ nhất định. Trong trường hợp này, bạn có thể sử dụng bộ lọc rest_route_for_term để cung cấp thông tin này. Điều này cho phép phân loại tùy chỉnh của bạn được định dạng đúng trong điểm cuối Tìm kiếm và cho phép các liên kết khám phá tự động.

<?php
/**
 * Register a genre post type, with REST API support
 *
 * Based on example at: https://codex.wordpress.org/Function_Reference/register_taxonomy
 */
add_action('init', 'my_book_taxonomy', 30);
function my_book_taxonomy() {
  $labels = array(
    'name'              => _x('Genres', 'taxonomy general name'),
    'singular_name'     => _x('Genre', 'taxonomy singular name'),
    'search_items'      => __('Search Genres'),
    'all_items'         => __('All Genres'),
    'parent_item'       => __('Parent Genre'),
    'parent_item_colon' => __('Parent Genre:'),
    'edit_item'         => __('Edit Genre'),
    'update_item'       => __('Update Genre'),
    'add_new_item'      => __('Add New Genre'),
    'new_item_name'     => __('New Genre Name'),
    'menu_name'         => __('Genre'),
  );
  $args = array(
    'hierarchical'          => true,
    'labels'                => $labels,
    'show_ui'               => true,
    'show_admin_column'     => true,
    'query_var'             => true,
    'rewrite'               => array('slug' => 'genre'),
    'show_in_rest'          => true,
    'rest_base'             => 'genre',
    'rest_controller_class' => 'WP_REST_Terms_Controller',
  );
  register_taxonomy('genre', array('book'), $args);
}
function my_plugin_rest_route_for_term($route, $term) {
  if ($term->taxonomy === 'genre') {
    $route = '/wp/v2/genre/' . $term->term_id;
  }
  return $route;
}
add_filter('rest_route_for_term', 'my_plugin_rest_route_for_term', 10, 2);
?>

Adding REST API Support To Existing Content Types

Nếu bạn cần thêm hỗ trợ API REST cho loại bài đăng tùy chỉnh hoặc phân loại tùy chỉnh mà bạn không kiểm soát, chẳng hạn như chủ đề hoặc plugin bạn đang sử dụng, bạn có thể sử dụng móc bộ lọc register_post_type_args đã tồn tại từ phiên bản WordPress 4.6.0.

<?php
/**
 * Add REST API support to an already registered post type.
 */
add_filter('register_post_type_args', 'my_post_type_args', 10, 2);
function my_post_type_args($args, $post_type) {
  if ('book' === $post_type) {
    $args['show_in_rest'] = true;
    // Optionally customize the rest_base or rest_controller_class
    $args['rest_base']             = 'books';
    $args['rest_controller_class'] = 'WP_REST_Posts_Controller';
  }
  return $args;
}
?>

Đối với các đơn vị phân loại tùy chỉnh thì gần như giống nhau. Bạn có thể sử dụng bộ lọc register_taxonomy_args đã tồn tại từ phiên bản WordPress 4.4.0.

<?php
/**
 * Add REST API support to an already registered taxonomy.
 */
add_filter('register_taxonomy_args', 'my_taxonomy_args', 10, 2);
function my_taxonomy_args($args, $taxonomy_name) {
  if ('genre' === $taxonomy_name) {
    $args['show_in_rest'] = true;
    // Optionally customize the rest_base or rest_controller_class
    $args['rest_base']             = 'genres';
    $args['rest_controller_class'] = 'WP_REST_Terms_Controller';
  }
  return $args;
}
?>

Last updated