Add featured image & alt text to WP REST API.

When getting data using the REST API from a separate site, this is a great snippet to add the data for post featured images as well as alt text (for accessibility purposes). Note: the image size has to be in existent on the site that you are pulling from, not the site that is the final destination.

function post_featured_image_json( $data, $post, $context ) {
     $featured_image_id = $data->data['featured_media']; // get featured image id
     $featured_image_url = wp_get_attachment_image_src( $featured_image_id, 'news-grid' );
     $alt = get_post_meta($featured_image_id, '_wp_attachment_image_alt', true);

     if( $featured_image_url ) {
          $data->data['featured_image_url'] = $featured_image_url[0];
          $data->data['featured_image_url_alt'] = $alt;
     }

     return $data;
}
add_filter( 'rest_prepare_post', 'post_featured_image_json', 10, 3 );

To get this data on the receiving site, use the appropriate url (this one gets posts tagged with a certain category) and set as a variable similar to:

$response = wp_remote_get( 'https://www.yourwebsitedomain.ca/wp-json/wp/v2/posts?categories=677' );

Use this variable to convert from JSON to the appropriate php content type, then use the variable $posts in a foreach loop.

$posts = json_decode( wp_remote_retrieve_body( $response ) );

An example of what that could look like with pulling the data from the other site would be:

<?php foreach ( $posts as $post ) {
     $newDate = date( "M d, Y", strtotime($post->date) );
?>
     <article class="blog-entry">
	<img src="<?php echo esc_url( $post->featured_image_url ); ?>" alt="<?php echo esc_html( $post->featured_image_url_alt ); ?>">
	<div class="data">
	     <p class="date"><?php echo esc_attr( $newDate ); ?></p>
	     <h3><?php echo esc_html( $post->title->rendered ); ?></h3>
	</div>
	<a class="button" href="<?php echo esc_url( $post->link ); ?>"><?php esc_html_e( 'Read more', 'domain' ); ?></a>
     </article>
<?php } ?>

Leave a Reply

Your email address will not be published.