最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I use Multi Media Uploader in the WordPress Plugins? - Stack Overflow

programmeradmin1浏览0评论

I try to add the multi uploading options in the wordpress plugins I repeated this code in the plugin(two times) only changing the id name.

                    <script language="JavaScript">
jQuery(document).ready(function($) {
    jQuery('#upload_image_button').click(function() {
        formfield = jQuery('#upload_image').attr('name');
        tb_show('', 'media-upload.php?type=image&TB_iframe=true');
        return false;
    });

    window.send_to_editor = function(html) {
        imgurl = jQuery('img', html).attr('src');
        jQuery('#upload_image').val(imgurl);
        tb_remove();
    };

});
                    </script>
<input id="upload_image" style=" margin-left:303px;" type="text" size="36" name="upload_image_template" value="<?php echo get_option('upload_image_template'); ?>" />
                        <input id="upload_image_button" type="button" value="Browse" />

Whenever I try to upload a image that media frame comes and the uploading process are did successfully. But Insert Into Post fetch the correct url but pasted in different input box. For example:

1) [text box1] [browse Button]
2) [text box2] [browse button]

When I upload image with Text Box One that [insert post] that image path is shown in [text box 2] I am Not Sure Whether the Problem is mine or that script didn't support multi file upload option.

I try to add the multi uploading options in the wordpress plugins I repeated this code in the plugin(two times) only changing the id name.

                    <script language="JavaScript">
jQuery(document).ready(function($) {
    jQuery('#upload_image_button').click(function() {
        formfield = jQuery('#upload_image').attr('name');
        tb_show('', 'media-upload.php?type=image&TB_iframe=true');
        return false;
    });

    window.send_to_editor = function(html) {
        imgurl = jQuery('img', html).attr('src');
        jQuery('#upload_image').val(imgurl);
        tb_remove();
    };

});
                    </script>
<input id="upload_image" style=" margin-left:303px;" type="text" size="36" name="upload_image_template" value="<?php echo get_option('upload_image_template'); ?>" />
                        <input id="upload_image_button" type="button" value="Browse" />

Whenever I try to upload a image that media frame comes and the uploading process are did successfully. But Insert Into Post fetch the correct url but pasted in different input box. For example:

1) [text box1] [browse Button]
2) [text box2] [browse button]

When I upload image with Text Box One that [insert post] that image path is shown in [text box 2] I am Not Sure Whether the Problem is mine or that script didn't support multi file upload option.

Share Improve this question edited Sep 14, 2014 at 5:53 M Khalid Junaid 64.5k10 gold badges92 silver badges119 bronze badges asked Jun 26, 2013 at 13:02 Vignesh PichamaniVignesh Pichamani 8,07022 gold badges80 silver badges117 bronze badges 3
  • Could you post the code for both input boxes? – Hieu Nguyen Commented Jul 13, 2013 at 15:53
  • You may be interested in this plugin wordpress.org/plugins/multi-image-upload – Tahir Yasin Commented Nov 19, 2013 at 8:18
  • Thanks @TahirYasin I look at the plugin this what i want. Thanks for sharing I am gonna give as five star rating in wordpress – Vignesh Pichamani Commented Nov 19, 2013 at 9:13
Add a comment  | 

5 Answers 5

Reset to default 16 +25

Here is the example how you can use the wordpress multimedia uploader for more than one field or as many fields. The JS code and html code looks like this

How it works

Add upload_image_button class on each upload button on the basis of this class click function triggers to fetch the wordpress multimedia uploader , see i have used the prev() property to get the previous element to the clicked one formfieldID=jQuery(this).prev().attr("id"); and then i have assigned the image url returned by uploader to formfieldID

 <input id="upload_image1" type="text" name="upload_image1" value="<?php echo $upload_image1;?>" />
    <input class="upload_image_button" type="button" value="Upload image 1" />

<input id="upload_image2" type="text"  name="upload_image2" value="<?php echo $upload_image2;?>" />
    <input class="upload_image_button" type="button" value="Upload image 2" />

<script type="text/javascript">
    //tb_show('', 'media-upload.php?TB_iframe=true');
    var upload_image_button=false;
    jQuery(document).ready(function() {

    jQuery('.upload_image_button').click(function() {
        upload_image_button =true;
        formfieldID=jQuery(this).prev().attr("id");
     formfield = jQuery("#"+formfieldID).attr('name');
     tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
        if(upload_image_button==true){

                var oldFunc = window.send_to_editor;
                window.send_to_editor = function(html) {

                imgurl = jQuery('img', html).attr('src');
                jQuery("#"+formfieldID).val(imgurl);
                 tb_remove();
                window.send_to_editor = oldFunc;
                }
        }
        upload_image_button=false;
    });


    })

</script>

Also make sure you have included the necessary JS and CSS files of the uploader for this you have to add an action

<?php
function my_admin_uploader_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('my-upload', WP_PLUGIN_URL.'/my-script.js', array('jquery','media-upload','thickbox'));
wp_enqueue_script('my-upload');
}

function my_admin_uploader_styles() {
wp_enqueue_style('thickbox');
}
add_action('admin_print_scripts', 'my_admin_uploader_scripts');
add_action('admin_print_styles', 'my_admin_uploader_styles'); 
?>

Note: Also take care of one thing when you assign the uploader to you input fields the control of uploader now assigns to the fields so when ever uploader will be called it assigns the image url to your text field , so this is the problem when you triggers the uploader you are unable to insert the images in the content area of the post for this solution you have to store the previous control in some where and when you are done with uploader then reassign the control of uploader to the previous function which i have provided in my JS code see below how it works

 var oldFunc = window.send_to_editor;
                    window.send_to_editor = function(html) {

                    imgurl = jQuery('img', html).attr('src');
                    jQuery("#"+formfieldID).val(imgurl);
                     tb_remove();
                    window.send_to_editor = oldFunc;
                    }

I have used this technique many times and it works perfect for me

Hope it makes sense

Here is my code based on Codex wp.media Example

Javascript

var sfieldGroup= '.field-group';   // top level parent  

var wpMediaUploader = { 
            sBtnAdd : ".upload-custom-wp-media",
            sBtnRemove : ".remove-custom-wp-media",
            sMediaData: ".media-data",
            sInput : ".custom-wp-media"
        };

 function wpMedia() {
        $(wpMediaUploader.sBtnAdd).on("click", function (event) {
            event.preventDefault();

            var self = $(this);
            var fieldGroup = self.parents(sfieldGroup);

            // Create a new media frame
            var frame = wp.media({
                title: "Select or Upload Media Of Your Chosen Persuasion",
                button: {
                    text: "Use this media"
                },
                multiple: false  // Set to true to allow multiple files to be selected
            });

            frame.on("select", function () {
                var attachment = frame.state().get("selection").first().toJSON();

                switch(attachment.mime){
                    case "image/jpeg" :
                    case "image/png" :
                    case "image/bmp" :
                    case "image/gif" :
                        fieldGroup.find(wpMediaUploader.sMediaData)
                            .append("<img src=\"" + attachment.url + "\" alt=\"\" />");
                        break;
                }

                $("<p/>",{
                    text: attachment.filename
                }).appendTo(fieldGroup.find(wpMediaUploader.sMediaData));

                fieldGroup.find(wpMediaUploader.sInput).val(attachment.id);
                fieldGroup.find(wpMediaUploader.sBtnAdd).addClass("hidden");
                fieldGroup.find(wpMediaUploader.sBtnRemove).removeClass("hidden");

                frame.close();
            });

            frame.open();
        });


        $(wpMediaUploader.sBtnRemove).on("click", function (event) {
            event.preventDefault();

            var self = $(this);
            var fieldGroup = self.parents(sfieldGroup); 


            // Clear out the preview image
            fieldGroup.find(wpMediaUploader.sMediaData).html("");

            // Un-hide the add image link
            fieldGroup.find(wpMediaUploader.sBtnAdd).removeClass("hidden");

            // Hide the delete image link
            fieldGroup.find(wpMediaUploader.sBtnRemove).addClass("hidden");

            // Delete the image id from the hidden input
            fieldGroup.find(wpMediaUploader.sInput).val("");
        });
    }

HTML

<div class="field-group">
    <div class="media-data"></div>
    <p class="hide-if-no-js">
        <a class="button upload-custom-wp-media" href="javascript:void(0)">Upload Media</a>
        <a class="button remove-custom-wp-media hidden" href="javascript:void(0)">Remove Selected Media</a>
    </p>
    <input id="test" name="test" class="custom-wp-media" value="" type="hidden">
</div>  

Tip
if you console.log frame,you will be exposed to API :)

            var frame = wp.media({
                title: "Select or Upload Media Of Your Chosen Persuasion",
                button: {
                    text: "Use this media"
                },
                multiple: false  // Set to true to allow multiple files to be selected
            });

Here, for the edit image to work, also to show other filter, hope it helps.

pa_uploader = wp.media({ 
            title: 'Choose Images',
            multiple: true,
            //frame: 'select',
            library: {
                filterable: 'all',
                editable: true,
                contentUserSetting: false
            },
            states: [
                new wp.media.controller.Library({
                    id:         'library',
                    title:      'Select Images',
                    priority:   40,
                    // toolbar:    'gallery',
                    filterable: 'all',
                    multiple:   'add',
                    editable:   true,
                    contentUserSetting: false,
                    library:  wp.media.query( _.defaults({
                        type: 'image'
                    }, {} ) )
                }),
                new wp.media.controller.EditImage({model: {}})
            ]
        });
       // pa_uploader.states.add([
       //       new wp.media.controller.EditImage({model: {}})
       //   ]);

        pa_uploader.on('content:render:edit-image', function() {
            var controller = pa_uploader.modal.controller;
                image = pa_uploader.state().get('image'),
                view = new wp.media.view.EditImage( { model: image, controller: controller } ).render();

            pa_uploader.content.set( view );

            // after creating the wrapper view, load the actual editor via an ajax call
            view.loadEditor();
        });
        pa_uploader.on('select', function(e){
            // This will return the selected image from the Media Uploader, the result is an object
            var selected_images = pa_uploader.state().get('selection');

                });
            });

        });

The answer from M Khalid Junaid is great but outdated.

See the codex page about wp.media : https://codex.wordpress.org/Javascript_Reference/wp.media.

It wasn't that hard...

See this revision history to see how I did... Basically what I did was adding this to my plugin:

function wp_gear_manager_admin_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_script('jquery');
}

function wp_gear_manager_admin_styles() {
wp_enqueue_style('thickbox');
}

add_action('admin_print_scripts', 'wp_gear_manager_admin_scripts');
add_action('admin_print_styles', 'wp_gear_manager_admin_styles');

And later this part in my JavaScript file:

<script language="JavaScript">
jQuery(document).ready(function() {
jQuery('#upload_image_button').click(function() {
formfield = jQuery('#upload_image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});

window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#upload_image').val(imgurl);
tb_remove();
}

});
</script>

And this in my html:

<tr valign="top">
    <td>Upload Image</td>
    <td><label for="upload_image">
        <input id="upload_image" type="text" size="36" name="upload_image" value="<?php echo $gearimage; ?>" />
        <input id="upload_image_button" type="button" value="Upload Image" />
        <br />Enter an URL or upload an image for the banner.
        </label>
    </td>
</tr>

You can just copy and paste this code to your plugin and see the magic.

发布评论

评论列表(0)

  1. 暂无评论