Advertisement
salmancreation

WP API featured image attachment

Jan 19th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.10 KB | None | 0 0
  1. I have found an answer https:\\wordpress.stackexchange.com/questions/241271/wp-rest-api-details-of-latest-post-including-featured-media-url-in-one-request I added this code to my functions file in the GET request location
  2.  
  3. add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
  4. function add_thumbnail_to_JSON() {
  5. //Add featured image
  6. register_rest_field('post',
  7.     'featured_image_src', //NAME OF THE NEW FIELD TO BE ADDED - you can call this anything
  8.     array(
  9.         'get_callback'    => 'get_image_src',
  10.         'update_callback' => null,
  11.         'schema'          => null,
  12.     )
  13.   );
  14. }
  15.  
  16. function get_image_src( $object, $field_name, $request ) {
  17. $feat_img_array = wp_get_attachment_image_src($object['featured_media'], 'thumbnail', true);
  18. return $feat_img_array[0];
  19. }
  20. then called ourHTMLString += '<img src=' + postsData[i].featured_image_src + '>';
  21.  
  22. ==============================
  23.  
  24.  
  25. Ah I just had this problem myself! And while _embed is great, in my experience it is very slow, and the point of JSON is to be fast :D
  26.  
  27. I have the following code in a plugin (used for adding custom post types), but I imagine you could put it in your theme's function.php file.
  28.  
  29. php
  30.  
  31. add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
  32. function add_thumbnail_to_JSON() {
  33. //Add featured image
  34. register_rest_field(
  35.    'post', // Where to add the field (Here, blog posts. Could be an array)
  36.    'featured_image_src', // Name of new field (You can call this anything)
  37.    array(
  38.        'get_callback'    => 'get_image_src',
  39.        'update_callback' => null,
  40.        'schema'          => null,
  41.         )
  42.    );
  43. }
  44.  
  45. function get_image_src( $object, $field_name, $request ) {
  46.  $feat_img_array = wp_get_attachment_image_src(
  47.    $object['featured_media'], // Image attachment ID
  48.    'thumbnail',  // Size.  Ex. "thumbnail", "large", "full", etc..
  49.    true // Whether the image should be treated as an icon.
  50.  );
  51.  return $feat_img_array[0];
  52. }
  53. Now in your JSON response you should see a new field called "featured_image_src": containing a url to the thumbnail.
  54.  
  55. Read more about modifying responses here:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement