I think i may be getting a little confused, but I have a list and a select button on each line. When the user clicks the button a modal shows up and I am trying to simple get an image (with a post_id) to display.

So in PHP I have this:

<img id="changeImage"src="
    echo $v[0]->user_image_id ? 
        wp_get_attachment_image_src( $v[0]->user_image_id,
            array( 'width' => 75, 'height' => 75 ))[0] :
            wp_get_attachment_url( 259 ); ?>" style="width: 75px; height: 75px"/>

This is part of the list, so each picture (avatar) is shown. Then a button is clicked and I already have the post_id with this code:

$('.selectedBtn').on('click', function (e) {
            var elm = $(this);
            var data;
            var dataArray = JSON.parse(sessionStorage.getItem('dataArray'));
            $.each(dataArray, function(k, v) {
                if(parseInt(v[0].wyol_list_id) === elm.data('wd')) {
                    data = v[0];
                    var imgid = v[0].user_image_id ? v[0].user_image_id : 259;
                    // USAGE:
                    preloadAttachment(imgid, function (attachment) {
                        console.log(wp.media.attachment(imgid).get('url')); // this also works
                        $('#wd_request_shoppers_image').prop('src',  wp.media.attachment(imgid).get('url'));
                            v[0].instructions ? $('#wd_request_shoppers_detail').text(v[0].instructions) : '';
                $('#closeModal').on('click', function () {

But all I get is this console.log error:

(index):352 Uncaught TypeError: Cannot read property 'attachment' of undefined

On this line: 352 if (wp.media.attachment(ID).get('url')) {

So has WP not got the ability to grab a url in WP?

Thanks in advance


2 Answers 2


You need to call wp_enqueue_media() else the wp object won't have a media option.

For example, go to WP Admin and pull up the JS console and type wp.media on the dashboard, it won't work. Try again on the media page, and this time it will work.


To be able to use the JavaScript-API, you first have to init all the needed JavaScript-Libraries and Styles:

  • thank you, but I am getting console response of "undefined" on both?
    – BadAddy
    Dec 3, 2017 at 20:51

With the help of Tom, I managed to get this working by using the wp.media.model which ended up like this:

var attachment = new wp.media.model.Attachment.get(imgid);
                        success: function (att) {
                            if (_.contains(['png', 'jpg', 'gif', 'jpeg'], att.get('subtype'))) {
                                $("#wd_request_shoppers_image").attr("src", att.attributes.sizes.thumbnail.url);

Not sure it's the quickest way of doing it, but works.

Hope it helps others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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