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

时间:2013-06-26 13:02:20

标签: javascript php wordpress-plugin wordpress

我尝试在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" />

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

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

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

5 个答案:

答案 0 :(得分:15)

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

如何运作

在每个上传按钮上添加upload_image_button类,基于此类click函数触发器来获取wordpress多媒体上传器,请参阅我已使用prev()属性获取前一个元素点击一个formfieldID=jQuery(this).prev().attr("id");,然后我将上传者返回的图片网址分配给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>

另外,请确保您已包含上传者的必要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'); 
?>
  

注意:分配上传器时也要注意一件事   你输入字段,上传者的控制现在分配给字段   当调用上传器时,它会将图像URL分配给您   文本字段,所以这是你触发上传器时的问题   无法在帖子的内容区域中插入图像   这个解决方案你必须将以前的控件存储在某些地方和   当你完成上传器然后重新分配上传器的控件   我在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;
                    }

我多次使用过这种技术,对我来说非常适合

希望它有意义

答案 1 :(得分:0)

不是那么难......

查看此修订历史,了解我的行为...... 基本上我所做的就是将它添加到我的插件中:

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:

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

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

您只需将此代码复制并粘贴到插件中即可看到魔力。

答案 2 :(得分:0)

在这里,要使编辑图像起作用,也要显示其他过滤器,希望它有所帮助。

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

                });
            });

        });

答案 3 :(得分:0)

answer from M Khalid Junaid很棒,但过时了。

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

答案 4 :(得分:0)

以下是基于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>  

提示
如果你是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
            });