0

I trying to grab the url of an attached photo using json. Im using the value of the data from the json "HousePhoto1". I then want to use that value to grab the value from the post_media data. This is what im using at the moment, but my javascript doesn't load correctly when I try this, but if i take to .guid away, my page loads but without any json data. I have also added a photo of my json.

    $.getJSON( "https://example.co.uk/wp-json/wp/v2/posts?&per_page=1&page=1", function( data ) {
      $.each( data, function( key, val ) {
        var photo = val.post_media[val.HousePhoto1].guid;
      });

    });

<img src="'+photo+'"/>

Image of my json

Oscar
  • 1
  • 3

1 Answers1

0

You were almost there. However, it looks like you are receiving an array back from your JSON response. Using a simplified dataset as my example, you can probably do something like this:

var data = [
  {
    HousePhoto1: "7073",
    post_media: {
      7073: {
        guid: "https://somecoolphoto.com"
      }
    }
  },
  {
    HousePhoto1: "7085",
    post_media: {
      7085: {
        guid: "https://anothercoolphoto.com"
      }
    }
  },
];

$.each(data, function(index, value) {
 var housePhotoId = value.HousePhoto1;
 var photo = value.post_media[housePhotoId].guid;
});

Also, if you are attempting to set multiple images, you cannot do it the way you currently are. You should dynamically insert the image into the DOM inside each iteration of the each loop via JavaScript.

Dan Zuzevich
  • 3,651
  • 3
  • 26
  • 39
  • Please let me know if you arent actually receiving an array back, and you only are dealing with an object. Im just assuming you are getting an array from your photo. – Dan Zuzevich Jun 26 '18 at 11:50