2

I have added a post meta to upload image using wordpress media uploader. Looks like it's a javascript work. I am no good in javascript. I took the js from here:

Here is the js code:

jQuery(document).ready(function($){

    // Instantiates the variable that holds the media library frame.
    var meta_image_frame;

    // Runs when the image button is clicked.
    $('#meta-image-button').click(function(e){

        // Prevents the default action from occuring.
        e.preventDefault();

        // If the frame already exists, re-open it.
        if ( meta_image_frame ) {
            wp.media.editor.open();
            return;
        }

        // Sets up the media library frame
        meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
            title: meta_image.title,
            button: { text:  meta_image.button },
            library: { type: 'image' }
        });

        // Runs when an image is selected.
        meta_image_frame.on('select', function(){

            //Grabs the attachment selection and creates a JSON representation of the model.
            var media_attachment = meta_image_frame.state().get('selection').first().toJSON();

            // Sends the attachment URL to our custom image input field.
            $('#meta-image').val(media_attachment.url);
        });

        // Opens the media library frame.
        wp.media.editor.open();
    });
});

I have an input box with id #meta-image. But it does not return the img url there. Instead, it puts the image url inside the main post editor. Any idea how can I get this to work?

1

I have solved this by changing wp.media.editor.open() to meta_image_frame.open().

It's now working fine. But I am not sure what was the error before.

  • Thanks, this fixed it for me also. I'm guessing the original code is slightly wrong and that this is how it was supposed to be. It would make sense because the on.('select'..) is attached to the meta_image_frame instance of the media editor, instead of the default wp.media.editor, whose 'Insert' button must post into the default editor by default, and our 'select' listener never fires... Just a guess though :) – CLuddy May 20 '14 at 14:56

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.