Question

I return data using the post id through AJAX. Now, what is the best way to "merge" the image thumbnail ( get_the_post_thumbnail( $id, 'medium' ) ) into the data returned from the server?

I need this as a single JSON object for passing it to a template (all this is working fine, just need the image as well).

The simple idea:

$post = get_post( $post_id );

$post['image'] = get_the_post_thumbnail( $post_id, 'medium' );

echo json_encode( $post );
Was it helpful?

Solution

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 );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top