WordPress Devs. I am new to WordPress and Web development. So far WordPress Rest API v2 works well. I was writing a custom API/route/endpoint for my project using the following function.

 get_post($postId);

Here the keys that are return as a response are mainly
ID,
post_author,
post_date,
post_date_gmt,
post_content,
post_title,
post_excerpt,
post_status,
comment_status.

However, the keys obtain from http://techdevfan.com/wp-json/wp/v2/posts are different from the custom API post object mainly
id
date,
date_gmt,
guid,
modified,
status,
link,
title.

There is completely no problem in serializing both the response. I just want to know is there any alternative to such problem so that there is no ambiguity in the keys for the two cases other than renaming the keys in $post object of a custom endpoint.

2 Answers
2

You can set your own keys in the JSON response array. It can be anything. Take a look at this simple example:

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');
    }
}

Now by visiting /wp-json/shubham/get_the_post?post_id=123 you will see the same structure as the default wp-json/wp/v2/posts for the post that has an ID of 123.

Leave a Reply

Your email address will not be published. Required fields are marked *