WordPress REST API默认的是支持post和page文章类型的,支持category以及tag分类法,但是很多时候我们会通过创建自定义分类法和自定义文章类型来丰富和方便我们的内容管理,那么这种情况下我们如何能让WordPress REST API也可以支持自定义分类法和自定义文章类型呢?
创建支持 WordPress REST API 的自定义文章类型
其实创建自定义文章类型时,如果想要让自定义文章类型支持 REST API 的方式获取数据,方法并不难,只需要增加几个参数类型。分别是:show_in_rest
,rest_base
,rest_controller_class
。第一个参数可以理解为是否在 REST API 中显示,所以参数值必须是 true;第二个参数可以理解为通过哪个 REST API 显示数据,所以参数值最好是自定义文章类型的别名,且必须是英文或是拼音,比如:bbs(表示论坛或是圈子);第三个参数可以理解为采用哪个 REST API 的控制类,所以参数值必须是使用文章的控制类:WP_REST_Posts_Controller。加上这三个参数项,基本上自定义文章类型的 REST API 就创建成功了。获取数据的 API 即为:https://网址域名/wp-json/wp/v2/bbs (rest_base设置的值)。
演示代码如下:
/* * WordPress REST API 支持自定义文章类型 */// 自定义文章类型add_action(\'init\', function () { $labels = array( \'name\' => \'圈子\', \'singular_name\' => \'bbs\', \'menu_name\' => \'圈子\', \'name_admin_bar\' => \'圈子\', \'add_new\' => \'添加\', \'add_new_item\' => \'新建\', \'edit_item\' => \'编辑\', \'new_item\' => \'新增\' ); $args = array( \'labels\' => $labels, \'public\' => true, \'show_ui\' => true, \'show_in_menu\' => true, \'query_var\' => true, \'rewrite\' => array( \'slug\' => \'bbs\' ), \'capability_type\' => \'post\', \'has_archive\' => false, \'exclude_from_search\' => true, \'menu_position\' => 8, \'supports\' => array(\'title\', \'editor\',\'author\',\'thumbnail\',\'comments\'), \'menu_icon\' => \'dashicons-googleplus\', \'show_in_rest\' => true, \'rest_base\' => \'bbs\', \'rest_controller_class\' => \'WP_REST_Posts_Controller\', ); register_post_type(\'bbs\',$args); });
创建支持 WordPress REST API 的自定义文章类型分类目录
创建了自定义文章类型难免有需要自定义文章类型的分类目录。如果想要自定义文章类型的分类目录支持 REST API ,也需要增加几个参数类型。同样是:show_in_rest
,rest_base
,rest_controller_class
。第一二个参数这里就不再详述,第三个参数和自定义文章类型里的表述其实差不多一样,只是控制类需要换成 Terms,所以参数值应该是:WP_REST_Terms_Controller。获取数据的 API 即为:https://网址域名/wp-json/wp/v2/topic (rest_base设置的值)。
演示代码如下:
/* * WordPress REST API 支持自定义分类法 */// 自定义文章类型分类add_action( \'init\',function () { $labels = array( \'name\' => _x( \'分类\', \'分类名称\' ), \'singular_name\' => _x( \'topic\', \'分类别名\' ), \'search_items\' => __( \'搜索分类\' ), \'all_items\' => __( \'所有分类\' ), \'parent_item\' => __( \'上级分类\' ), \'parent_item_colon\' => __( \'父级分类:\' ), \'edit_item\' => __( \'编辑\' ), \'update_item\' => __( \'更新\' ), \'add_new_item\' => __( \'新建\' ), \'new_item_name\' => __( \'新增\' ), \'menu_name\' => __( \'分类\' ), ); $args = array( \'hierarchical\' => true, \'labels\' => $labels, \'show_ui\' => true, \'show_admin_column\' => true, \'query_var\' => true, \'rewrite\' => array( \'slug\' => \'topic\' ), \'show_in_rest\' => true, \'rest_base\' => \'topic\', \'rest_controller_class\' => \'WP_REST_Terms_Controller\', ); register_taxonomy( \'topic\', array( \'bbs\' ), $args );}, 30 );
基本上到此为止,自定义文章类型的 WordPress REST API 相关项就已经完成了,其他的数据,则根据自己的需要进行拓展即可,比如自定义文章类型的 TAG 和自定义标签项等,这里就不一一详述了
回复
暂无评论