0

I was looking for a solution to get the image url starting from the uploaded media id.

I'm using a custom field to specify which images to show on a post page. Then I retrieve the images ids with the REST api, and I need to create a gallery of images, based on the retrieved ids.

Does anybody know how to retrieve the image url, based on the image id(using an AJAX call from a .js file)?
Something like the WP php version of wp-get-attachment-image.

1

You can use REST API to retrieve media item. Just send GET request to this address (change example.com to your site):

http://example.com/wp-json/wp/v2/media/<id>

If you pass correct ID, then you'll get all info regarding that media file. For example I get something like this for one of my image files:

{
  "id": 546,
  "date": "2019-01-23T11:22:15",
  "date_gmt": "2019-01-23T10:22:15",
  "guid": {
    "rendered": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
  },
  "modified": "2019-01-23T11:22:15",
  "modified_gmt": "2019-01-23T10:22:15",
  "slug": "my-icon",
  "status": "inherit",
  "type": "attachment",
  "link": "https://example.com/my-icon/",
  "title": {
    "rendered": "my-icon"
  },
  "author": 1,
  "comment_status": "open",
  "ping_status": "closed",
  "template": "",
  "meta": [],
  "description": {
    "rendered": "<p class=\"attachment\"><a href='https://example.com/wp-content/uploads/2019/01/my-icon.png'><img width=\"300\" height=\"300\" src=\"https://example.com/wp-content/uploads/2019/01/my-icon.png\" class=\"attachment-medium size-medium\" alt=\"\" srcset=\"https://example.com/wp-content/uploads/2019/01/my-icon.png 300w, https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png 150w\" sizes=\"(max-width: 300px) 100vw, 300px\" /></a></p>\n"
  },
  "caption": {
    "rendered": ""
  },
  "alt_text": "",
  "media_type": "image",
  "mime_type": "image/png",
  "media_details": {
    "width": 300,
    "height": 300,
    "file": "2019/01/my-icon.png",
    "sizes": {
      "thumbnail": {
        "file": "my-icon-150x150.png",
        "width": "150",
        "height": "150",
        "mime_type": "image/png",
        "source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-150x150.png"
      },
      "portfolio-thumbnail": {
        "file": "my-icon-300x240.png",
        "width": "300",
        "height": "240",
        "mime_type": "image/png",
        "source_url": "https://example.com/wp-content/uploads/2019/01/my-icon-300x240.png"
      },
      "full": {
        "file": "my-icon.png",
        "width": 300,
        "height": 300,
        "mime_type": "image/png",
        "source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png"
      }
    },
    "image_meta": {
      "aperture": "0",
      "credit": "",
      "camera": "",
      "caption": "",
      "created_timestamp": "0",
      "copyright": "",
      "focal_length": "0",
      "iso": "0",
      "shutter_speed": "0",
      "title": "",
      "orientation": "0"
    }
  },
  "post": null,
  "source_url": "https://example.com/wp-content/uploads/2019/01/my-icon.png",
  "_links": {
    "self": [
      {
        "attributes": [],
        "href": "https://example.com/wp-json/wp/v2/media/546"
      }
    ],
    "collection": [
      {
        "attributes": [],
        "href": "https://example.com/wp-json/wp/v2/media"
      }
    ],
    "about": [
      {
        "attributes": [],
        "href": "https://example.com/wp-json/wp/v2/types/attachment"
      }
    ],
    "author": [
      {
        "attributes": {
          "embeddable": true
        },
        "href": "https://example.com/wp-json/wp/v2/users/1"
      }
    ],
    "replies": [
      {
        "attributes": {
          "embeddable": true
        },
        "href": "https://example.com/wp-json/wp/v2/comments?post=546"
      }
    ]
  }
}
  • This is great, but unfortunatelly it retrieves only the media file name, without extension. – n1kkou Feb 23 at 19:46
  • Oh, my bad, it retrieves a full image dataset! – n1kkou Feb 23 at 19:59
0

You can create your own AJAX action to handle this:

add_action( 'wp_ajax_get_attachment_src_details', 'smyles_get_attachment_src_details' );

function smyles_get_attachment_src_details() {

    check_ajax_referer( 'smyles_get_attachment_src_details', 'smyles_get_attachment_src_details' );
    $user_id = get_current_user_id();

    if ( empty( $user_id ) ) {
        wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );
        return;
    }

    $attach_id = absint( $_POST['attachment_id'] );
    $size = array_key_exists( 'size', $_POST ) ? sanitize_text_field( $_POST['size'] ) : 'thumbnail';

    if( $source = wp_get_attachment_image_src( $attach_id, $size ) ){
        wp_send_json_success( $source );
    } else {
        wp_send_json_error();
    }
}

If you don't care if user is logged in you can remove that code, but you should still keep the nonce handling (ALWAYS think security first!) as this prevents allowing external calls (not from your site) to your endpoints

The return value will be JSON with - url, width, height, is_intermediate

  • While this approach gets a bonus point from a security POV, I needed to reach that images from a javascript file(where I cannot call wp built in functions or anything related to php methods) – n1kkou Feb 25 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.