Dùng REST API cho nội dung tùy chỉnh

Cập nhật lần cuối vào

WordPress đang trong giao đoạn chuẩn bị cho các bước phát triển mới và WP REST API là một trong những tính năng đặc biệt mà người dùng mong đợi, với REST API bạn hoàn toàn có thể làm được mọi thứ, từ truy vấn dữ liệu, tạo và chỉnh sửa dữ liệu trên blog một cách dễ dàng thông qua giao thức HTTP.

WP REST API logo

Kể từ phiên bản 4.4 thì WordPress đã chính thức hỗ trợ REST API, bạn có thể ứng dụng chức năng này để xây dựng data server, tạo server để kiểm tra license từ xa,… có rất nhiều tiện ích mà người dùng có thể tạo ra.

Trong bài này mình sẽ hướng dẫn cho các bạn cách sử dụng REST API cho custom post type và custom taxonomy, nếu bạn cần truy vấn nội dung tùy chỉnh dưới dạng JSON thì bài viết này sẽ giúp ích cho bạn.

Dùng REST API cho custom post type

Mặc định thì khi bạn tạo post type mới hệ thống sẽ không thể truy vấn nội dung của bạn được. Để cho phép custom post type có thể truy vấn qua REST API thì bạn phải thêm tham số show_in_rest vào trong hàm register_post_type.

Sau khi bạn thêm tham số show_in_rest là true trong hàm đăng ký post type mới thì bạn hoàn toàn có thể truy vấn dữ liệu của bạn. Ví dụ như mình đăng ký custom post type là book thì bây giờ bạn sẽ truy vấn theo kiểu wp-json/wp/v2/book.

Nếu bạn muốn thay đổi tên truy vấn book thành book api thì bạn sẽ tiếp tục dùng tham số rest_base trong hàm đăng ký post type bên trên. Ngoài ra, bạn cũng có thể thay đổi hàm điều khiển kết quả trả về của truy vấn bằng tham số rest_controller_class, nếu bạn muốn dùng hàm của riêng mình thì bạn phải tạo class thừa kế từ class WP_REST_Controller, mặc định REST API sẽ dùng class WP_REST_Posts_Controller.

/**
 * Register a book post type, with REST API support
 *
 * Based on example at: http://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'          => 'books-api',
  		'rest_controller_class' => 'WP_REST_Posts_Controller',
  		'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
  	);
  
  	register_post_type( 'book', $args );
}

Nếu bạn muốn cập nhật cho post type sẵn có thì bạn dùng như ví dụ bên dưới:

/**
 * Add REST API support to an already registered post type.
 */
add_action( 'init', 'my_custom_post_type_rest_support', 25 );
function my_custom_post_type_rest_support() {
	global $wp_post_types;

	// be sure to set this to the name of your post type!
	$post_type_name = 'book';
	if( isset( $wp_post_types[ $post_type_name ] ) ) {
		$wp_post_types[$post_type_name]->show_in_rest = true;
		$wp_post_types[$post_type_name]->rest_base = $post_type_name . '-api';
		$wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
	}

}

Trong 2 ví dụ bên trên, mình dùng rest_base tùy chỉnh, bạn sẽ truy vấn book theo dạng wp-json/wp/v2/book-api thay vì wp-json/wp/v2/book như mặc định.

Dùng REST API cho custom taxonomy

Cái này cũng tương tự như trường hợp dùng REST API cho custom post type, để sử dụng REST API cho custom taxonomy thì bạn cũng dùng 3 tham số như bên trên đó là show_in_rest, rest_baserest_controller_class.

Có điểm khác chút là bạn sẽ sử dụng hàm register_taxonomyrest_controller_class bạn sẽ dùng WP_REST_Terms_Controller, nếu bạn muốn viết class khác cũng được, nhưng phải tuân thủ theo quy định.

Bên dưới là ví dụ đăng ký custom taxonomy mới cho post type book bên trên, có hỗ trợ REST API:

/**
 * 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 );

}

/**
 * Add REST API support to an already registered taxonomy.
 */
add_action( 'init', 'my_custom_taxonomy_rest_support', 25 );
function my_custom_taxonomy_rest_support() {
	global $wp_taxonomies;

	//be sure to set this to the name of your taxonomy!
	$taxonomy_name = 'genre';

	if ( isset( $wp_taxonomies[ $taxonomy_name ] ) ) {
		$wp_taxonomies[ $taxonomy_name ]->show_in_rest = true;
		$wp_taxonomies[ $taxonomy_name ]->rest_base = $taxonomy_name;
		$wp_taxonomies[ $taxonomy_name ]->rest_controller_class = 'WP_REST_Terms_Controller';
	}


}

Trong đoạn ví dụ này mình tích hợp cả 2 trường hợp, nếu bạn đăng ký mới taxonomy thì không cần hàm cập nhật, nếu bạn dùng hàm cập nhật thì không cần đăng ký mới custom taxonomy nhé.

Như vậy, qua bài viết này bạn đã có thể hiểu thêm về WP REST API, bạn hoàn toàn có thể tạo bất kỳ custom post type nào hoặc bất kỳ custom taxonomy nào, tất cả đều có thể truy vấn được thông qua REST API. Chúc bạn thành công.

Theo dõi
Thông báo của
guest

0 Comments
Phản hồi nội tuyến
Xem tất cả bình luận