Getting Featured Images from the WordPress API

WordPress now comes pre-installed with an API. This API allows you to access different data end-points to your wordpress instance.

So instead of starting up a laggy browser, logging into your dashboard, and waiting 15 minutes for PHP to respond… You can write your own apps that deal with the WordPress API to quickly create, read, update, and delete posts.

By default, the WordPress API is turned on and is accessible. You access the API by going to the main endpoint, which is

http://yourdomain.com/wp-json/wp/v2/

For example, the API on this site is

http://1000daysofcode.com/wp-json/wp/v2/

But lots of API beginner’s always ask

“Where is the WordPress API image end point?”

Also by default, the WordPress API keeps the amount of data it processes as light as possible. So objects like images aren’t sent with any API responses. To access your image endpoint, you have to make a request to the API, but have to add a query string.

So to have WordPress send you a data response that includes the image, the endpoint is:

http://yourdomain.com/wp-json/wp/v2?_embed

Assuming you are making an AJAX call, you can receive the JSON blob with javascript as a JSON blob by using the json.PARSE(data) method.

var url="https://www.yourdomain.com/wp-json/wp/v2/posts/"+story_param+"?_embed";


$.get(url, function(data){

    // This turns response object from a string to a Javascript Object

    var data = JSON.parse(data); 

    // Once in a object array you cam access the image by using the following array indexes

    var image = data["_embedded"]["wp:featuredmedia"][0];

}

You can see all the API enpoints here as well.

Happy coding!

 

 

 

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *