How to get featured post title & image using JSON API?

I made a shortcut to my image by adding it directly to the API response.


//Add in functions.php, this hook is for  my 'regions' post type
add_action( 'rest_api_init', 'create_api_posts_meta_field' );

function create_api_posts_meta_field() {
  register_rest_field( 'regions', 'group', array(
         'get_callback'    => 'get_post_meta_for_api',
         'schema'          => null,
      )
  );
}

//Use the post ID to query the image and add it to your payload. 


function get_post_meta_for_api( $object ) {
  $post_id = $object['id'];
  $post_meta = get_post_meta( $post_id );
  $post_image = get_post_thumbnail_id( $post_id );      
  $post_meta["group_image"] = wp_get_attachment_image_src($post_image)[0];


  //var_dump(wp_get_attachment_image($post_image)); die();
  //Different image codex return different values, narrow in on what you want

  return $post_meta;
}

Leave a Comment