I have got an attachment id, but I need an url. How can I get an url from the attachment object?

// When an image is selected, run a callback.
frame.on( 'select', function() {
    // Grab the selected attachment.
    var attachment = frame.state().get('selection').first();
    $('#' + id).val(attachment.id);
}); 

toJSON() function convert it. Now it works.

jQuery(document).ready(function($) {
var frame;

// Build the choose from library frame.
$(document).on("click", ".upload_image_button", function() {
    var id = $(this).attr('id').replace('_b', '');  

    if ( frame ) {
        frame.open();
        return;
    }

    // Create the media frame.
    frame = wp.media.frames.meta_image_frame = wp.media({
        // Tell the modal to show only images.
        library: {
            type: 'image'
        },
    });

    // When an image is selected, run a callback.
    frame.on( 'select', function() {
        // Grab the selected attachment.
        attachment = frame.state().get('selection').first().toJSON();
        $('#' + id).val(attachment.url);
    });

    frame.open();
    });
});

2 Answers
2

You have to convert attachment variable to JSON object using toJSON() . Then you can its property.

use

attachment = frame.state().get('selection').first().toJSON();

instead of

attachment = frame.state().get('selection').first();

Tags:

Leave a Reply

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