javascript 如何在 WordPress 插件中使用多媒体上传器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17320802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:53:07  来源:igfitidea点击:

How can I use Multi Media Uploader in the WordPress Plugins?

javascriptphpwordpress-pluginwordpress

提问by Vignesh Pichamani

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.

我尝试在 wordpress 插件中添加多上传选项我在插件中重复了这段代码(两次),只更改了 id 名称。

                    <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:

每当我尝试上传媒体帧出现的图像并且上传过程成功完成时。但是 Insert Into Post 获取正确的 url 但粘贴在不同的输入框中。例如:

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.

当我使用文本框一上传图像时,[insert post]该图像路径显示在[text box 2]我不确定是我的问题还是该脚本不支持多文件上传选项中。

回答by M Khalid Junaid

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

以下是如何将 wordpress 多媒体上传器用于多个字段或多个字段的示例。该JS代码和HTML代码如下所示

How it works

怎么运行的

Add upload_image_buttonclass on each upload button on the basis of this class clickfunction 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

upload_image_button在这个类click函数触发器的基础上在每个上传按钮上添加类以获取 wordpress 多媒体上传器,看到我已经使用该prev()属性将前一个元素获取到单击的元素formfieldID=jQuery(this).prev().attr("id");,然后我已将上传器返回的图像 url 分配给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 JSand CSSfiles of the uploader for this you have to add an action

还要确保您已包含上传者的必要文件JSCSS文件,为此您必须添加一个操作

<?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

注意:当您将上传器分配给您的输入字段时,还要注意一件事,上传器的控制现在分配给这些字段,因此当上传器被调用时,它会将图像网址分配给您的文本字段,所以这就是您的问题触发上传器 您无法为此解决方案在帖子的内容区域中插入图像 您必须将以前的控件存储在某些地方以及当您完成上传器时,然后将上传器的控制权重新分配给我拥有的先前功能在我的 JS 代码中提供,请参阅下面的工作原理

 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

希望这是有道理的

回答by Umair Hamid

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:

后来这部分在我的 JavaScript 文件中:

<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:

这在我的 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.

您可以将此代码复制并粘贴到您的插件中并查看其神奇之处。

回答by Eilluj

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');

                });
            });

        });

回答by gordie

The answer from M Khalid Junaidis great but outdated.

M Khalid Junaid回答很好,但已经过时了。

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

请参阅有关 wp.media 的 Codex 页面:https://codex.wordpress.org/Javascript_Reference/wp.media 。

回答by gordie

Here is my code based on Codex wp.media Example

这是我基于Codex wp.media Example 的代码

Javascript

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

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 :)

提示,
如果您使用 console.log 框架,您将接触到 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
            });