2

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();
    });
});
1
  • If you got an answer - please add it as such and not as edit to your question. This is encouraged by the system and will be rewarded. Thanks
    – kaiser
    Commented Dec 16, 2014 at 4:33

2 Answers 2

1

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();
2

If you have attachment id then you can call wp_get_attachment_url function to get URL of attachment.

<?php wp_get_attachment_url( $id ); ?>

wp_get_attachment_url function accept ID.

Example usage... for attachment id 12.

<?php echo wp_get_attachment_url( 12 ); ?>

It will output something like http://example.net/wp-content/uploads/filename

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.