WordPress教程

WordPress创建post type自定义文章类型时添加rest api支持

阿里云

如果你需要用 WordPress 的 rest api 做小程序或者 APP,那你很大概率会用到 rest api,那么 WordPress 创建 post type 自定义文章类型时添加 rest api 支持呢?通常情况下注册的 post type 是并不能支持 rest api 访问的,你需要做额外的设置。,下面是实例代码:

  1. /**
  2.  * 创建post type时添加rest api支持
  3.  *
  4.  */
  5. add_action( 'init', 'my_book_cpt' );
  6. function my_book_cpt() {
  7.   $labels = array(
  8.     'name'               => _x( 'Books', 'post type general name', 'your-plugin-textdomain' ),
  9.     'singular_name'      => _x( 'Book', 'post type singular name', 'your-plugin-textdomain' ),
  10.     'menu_name'          => _x( 'Books', 'admin menu', 'your-plugin-textdomain' ),
  11.     'name_admin_bar'     => _x( 'Book', 'add new on admin bar', 'your-plugin-textdomain' ),
  12.     'add_new'            => _x( 'Add New', 'book', 'your-plugin-textdomain' ),
  13.     'add_new_item'       => __( 'Add New Book', 'your-plugin-textdomain' ),
  14.     'new_item'           => __( 'New Book', 'your-plugin-textdomain' ),
  15.     'edit_item'          => __( 'Edit Book', 'your-plugin-textdomain' ),
  16.     'view_item'          => __( 'View Book', 'your-plugin-textdomain' ),
  17.     'all_items'          => __( 'All Books', 'your-plugin-textdomain' ),
  18.     'search_items'       => __( 'Search Books', 'your-plugin-textdomain' ),
  19.     'parent_item_colon'  => __( 'Parent Books:', 'your-plugin-textdomain' ),
  20.     'not_found'          => __( 'No books found.', 'your-plugin-textdomain' ),
  21.     'not_found_in_trash' => __( 'No books found in Trash.', 'your-plugin-textdomain' )
  22.   );
  23.  
  24.   $args = array(
  25.     'labels'             => $labels,
  26.     'description'        => __( 'Description.', 'your-plugin-textdomain' ),
  27.     'public'             => true,
  28.     'publicly_queryable' => true,
  29.     'show_ui'            => true,
  30.     'show_in_menu'       => true,
  31.     'query_var'          => true,
  32.     'rewrite'            => array( 'slug' => 'book' ),
  33.     'capability_type'    => 'post',
  34.     'has_archive'        => true,
  35.     'hierarchical'       => false,
  36.     'menu_position'      => null,
  37.     'show_in_rest'       => true,
  38.     'rest_base'          => 'books',
  39.     'rest_controller_class' => 'WP_REST_Posts_Controller',
  40.     'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
  41.   );
  42.  
  43.   register_post_type( 'book', $args );
  44. }
也想出现在这里?联系我们
创客主机

WordPress 创建 post type 自定义文章类型时添加 rest api 支持

已有 275 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!