Reputation: 765
This is a 2 part question:
1) I am trying to take these elements from WordPress' REST API and set them into an array (map_locations
) which I've created. Now, I've got the $.ajax
portion of the function working (meaning when I console.log it, I see [my_data]
, but the later half doesn't.
map_locations.forEach( function( map_item ) {
console.log('hi');
}
I'm expecting the above to log to the console at least once, however I get nothing. The reason I have console.log()
is just to see if I'm getting anything first. Is there something in my entire code that I have setup incorrectly? Is there a better way to do what I'm doing?
2) How do I access the data within the $.ajax
function for the media? I have tried to use the following to set it, but I error out at ['0']
image: post._embedded['wp:featuredmedia']['0'].media_details.sizes.thumbnail.
Full Code:
(function($) {
var map_locations = [];
// Works
$.ajax( {
url: '/wp-json/wp/v2/map-api?_embed',
method: 'GET',
success: function( data ) {
// Run through a foreach loop and setup the post data.
data.forEach( function( post ) {
map_locations.push( {
// Set fields
id: post.id,
title : post.title.rendered,
lat: post.acf.location_post_lat,
lng: post.acf.location_post_long,
content: post.content.rendered,
address: post.acf.address,
address2: post.acf.address2,
city: post.acf.city,
state: post.acf.state,
zip: post.acf.zip,
phone: post.acf.phone,
website: post.acf.website,
cat: post['map-cat'],
} )
} )
},
cache : false
} );
console.log( map_locations );
map_locations.forEach( function(post_item) {
console.log('hi');
} );
})(jQuery);
Upvotes: 0
Views: 501
Reputation: 3520
1) the reason which you're getting nothing in your function:
map_locations.forEach( function(post_item) {
console.log('hi');
} );
is because you're calling the the map_locations
array before the promise has been resolved, in that case you could refactor your code and call inside the promise.
2) You're taking the zero in the second square parenthesis as string this must be a number, try this:
image: post._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail.
Upvotes: 1