自己回答问题。我希望这能帮助一些人。
1。如何为自定义帖子类型创建REST API如果要创建新的自定义帖子类型,请确保在参数数组中将此选项设置为true:
show_in_rest\' => true,
如果您的自定义帖子来自主题或插件,并且您希望为其启用rest api,则将此代码添加到子主题函数中。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 ( \'course\' === $post_type ) {
$args[\'show_in_rest\'] = true;
// Optionally customize the rest_base or rest_controller_class
$args[\'rest_base\'] = \'course\';
$args[\'rest_controller_class\'] = \'WP_REST_Posts_Controller\';
}
return $args;
}
2。如何为自定义查询创建端点
假设您要运行一些wp查询,需要发送一个自定义参数&;从rest API访问该查询
add_action(\'rest_api_init\', function () {
register_rest_route( \'namespace/v2\', \'events/(?P<id>\\d+)\',array(
\'methods\' => \'GET\',
\'callback\' => \'get_events_from_id\'
));
});
//Now create a function to return your custom query results
function get_events_from_id($request){
$id = $request[\'id\'];
// Custom WP query query
$args_query = array(
\'post_type\' => array(\'events\'),
\'order\' => \'DESC\',
);
$query = new WP_Query( $args_query );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$data = //do your stuff like
}
} else {
}
return $data;
wp_reset_postdata();
}