Search code examples
javascriptwordpresswordpress-gutenberggutenberg-blocks

How to get image URL and metrics by ID from Gutenberg frontend


How can I query the URL, height, width and alt text of an image by its media id using JavaScript?

There's a way to do so by using the PHP function wp_get_attachment_metadata.

Is there a JavaScript function I can call in frontend to get the image metadata (for both newly uploaded media and previously uploaded media)?


Solution

  • The WordPress REST API can be used to retrieve the media details with JavaScript. There is a media endpoint which is very useful if you have the ID:

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

    The JSON returned contains all the information about the media, including:

    {
        "alt_text": "Lorem ipsum...", 
        "source_url": "http://...",
        "media_details": {
            "height": 400, 
            "width": 600
         }
        ...
    }
    

    Reference: REST API Handbook / Reference / Media