您可以在JSON响应数组中设置自己的密钥。它可以是任何东西。看看这个简单的例子:
add_action( \'rest_api_init\', function () {
register_rest_route( \'shubham\', \'/get_the_post/\', array(
\'methods\' => \'GET\',
\'callback\' => \'get_posts_by_rest\'
) );
});
// Callback function
function get_posts_by_rest( ){
// Get the post id from the URL and validate it
if( isset( $_REQUEST[\'post_id\'] ) && filter_var( $_REQUEST[\'post_id\'] , FILTER_VALIDATE_INT ) ) {
$id = abs( $_REQUEST[\'post_id\'] );
} else {
return __(\'Please enter a post ID.\',\'text-domain\');
}
// Fetch the post
$post = get_post( $id );
// Check if the post exists
if( $post ) {
// Now, form our own array
$data = array();
$data[\'id\'] = $post->ID;
$data[\'date\'] = $post->post_date;
$data[\'date_gmt\'] = $post->post_date_gmt;
$data[\'guid\'] = $post->guid;
$data[\'modified\'] = $post->post_modified
$data[\'modified_gmt\'] = $post->post_modified_gmt;
$data[\'slug\'] = $post->post_name;
$data[\'status\'] = $post->post_status;
$data[\'title\'] = $post->post_title;
$data[\'content\'] = $post->post_content;
$data[\'excerpt\'] = $post->post_excerpt;
// Add the rest of your content
// Return the response
return $data;
} else {
return __(\'Invalid post ID\',\'text-domain\');
}
}
现在通过访问
/wp-json/shubham/get_the_post?post_id=123
您将看到与默认结构相同的结构
wp-json/wp/v2/posts
对于ID为123的帖子。