The reason that your idea doesn’t work is, get_post
returns a post object, not an array (if not set manually).
This is a quote from WordPress code reference:
When $output is OBJECT, a WP_Post instance is returned.
Which is the default output type for get_post()
.
If you need to implement an array of data and then encode it using JSON, do this:
// Let's retrieve the post object
$post = get_post( $post_id );
// Set up the post data to use in our code
setup_postdata($post);
// Create an empty array for the data
$json_input = array();
$json_input['image'] = get_the_post_thumbnail( $post->ID, 'medium' );
$json_input['excerpt'] = get_the_excerpt();
$json_input['content'] = get_the_content();
$json_input['title'] = get_the_title();
// Now, we should reset the post data to avoid conflict
wp_reset_postdata();
// Our data is ready to be encoded, just, DO IT!
$json = json_encode($json_input);
However, you can set the output of get_post()
to return an array, by changing the second argument:
get_post( $post_id, ARRAY_A );