Get attachment/image info in JS

The question:

Is there a specific method to get attachment/image info in JS?
I have an attachment id and before I use any

add_action("wp_ajax_get_image_info", "get_image_info");

I would like to see if there is a native method for doing this trough JS only.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Long story short, you can get info about an attachment by using function. This will give you complete data as long as this attachment is already loaded by another script or an popup.

If the data is not yet loaded, you can load it using .fetch() method on attachment, which works because it is a Backbone.Collection. It is a Collection because an attachment may have multiple selected files in it.

// preload your attachment (data) {
  // preloading finished
  // after this you can use your attachment normally'url');

Easy way of doing preloading:

function preloadAttachment(ID, callback) {
  // if it doesn't have URL we probably have to preload it
  if ('url')) { () {



preloadAttachment(10, function (attachment) {
  console.log('url')); // this also works

And that’s how you will want to go about preloading more than one attachment, in a single AJAX request.

// An array of attachments you may want to preload
var attachment_ids = [10, 11, 12, 13];{ post__in: attachment_ids })
  .then(function () {
    // You attachments here normally
    // You can safely use any of them here'url');

Note the fact that the AJAX request performed by is paginated. If you need a robust solution for loading lots and lots of attachments you should go about parsing each page with hasMore() and more() methods.


I have used this method before finding out about but it has the penalty of making one request per preloaded attachment. But it also has a nice feature — it doesn’t make any request if all of the attachments that need to be preloaded are already in the fetched state.

function preloadMultipleAttachments(attachment_ids) {
    // I'd rather use Promise.all() here but they do not work with
    // jQuery deferreds :/
    if (jQuery.when.all===undefined) {
        jQuery.when.all = function(deferreds) {
            var deferred = new jQuery.Deferred();
            $.when.apply(jQuery, deferreds).then(
                function() {
                function() {

            return deferred;

    return jQuery.when.all(
        attachment_ids.filter(function (attachment_id) {
            return !'url');
        }).map(function (id) {

Method 2

Jetpack has a JSON API that allows you to query pretty much everything in a given install.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment