WordPress后台定制-在自定义字段面板中调用媒体/图片上传对话框

本站所有文章均为博主人工写作,绝无AI辅助成分,请放心参阅。

在WordPress自定义字段面板中,有时候我们需要上传图片,或者附件,并且获取它的URL作为这个自定义字段的值。这个属于WordPress比较高级的后台定制了,但却是很常见的。很多插件都提供了解决方案,今天我把代码扒出来,可以直接用在主题的后台中。
把原本自定义字段的的input标签换成如下这段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<input type="text" name="custom_media_url" id="custom_media_url" value="<?php echo $custom_meta_url; ?>"  style="width:100%" />
<input type="button" value="Upload" class="custom_media_bt" />
<script>
jQuery(document).ready(function() {
    //input.custom_media_bt为上传按钮
    jQuery('input.custom_media_bt').click(function() {
        //custom_media_url为文本域
         targetfield = jQuery(this).prev('#custom_media_url'); 
         tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
         return false;
    });
    window.send_to_editor = function(html) {
         imgurl = jQuery('img',html).attr('src');
         jQuery(targetfield).val(imgurl);  
         tb_remove();
    }
});
</script>

以上代码的custom_meta_url就是自定义字段的名称了,对应需做修改。
用了这段代码效果如图,上传文件的输入框和按钮:
WordPress自定义字段面板中调用媒体上传对话框-界面形式
点击按钮弹出媒体对话框:
WordPress自定义字段面板中调用媒体上传对话框-老式的对话框
上传完毕后会在input输入框中出现上传的媒体的URL。

从WordPress3.5开始,我们有了更先进的媒体管理工具,不用就浪费了,于是上面这段代码可以升级成这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<img class="custom_media_image" src="" style="width:30px; height:30px" />
<span class="custom_media_id" name="attachment_id"></span>
<input class="custom_media_url" type="text" name="attachment_url" value="">
<input type="button" value="Upload" class="custom_media_upload" />
<script>
jQuery('.custom_media_upload').click(function() {
    var send_attachment_bkp = wp.media.editor.send.attachment;
    wp.media.editor.send.attachment = function(props, attachment) {
        jQuery('.custom_media_image').attr('src', attachment.url);
        jQuery('.custom_media_url').val(attachment.url);
        jQuery('.custom_media_id').html(attachment.id);
        wp.media.editor.send.attachment = send_attachment_bkp;
    }
    wp.media.editor.open();
    return false;       
});
</script>

这样点击上传按钮,就用上了最新的媒体管理工具,很带劲:
WordPress自定义字段面板中调用媒体上传对话框 - 最新的媒体管理工具
这段代码顺便让自定义字段的面板变得更好用了,上传完毕后显示预览图和附件的ID。
WordPress自定义字段面板中调用媒体上传对话框 - 最终效果

参考文章:http://stackoverflow.com/questions/13847714/wordpress-3-5-custom-media-upload-for-your-theme-options

本站所有文章均为原创,欢迎转载,请注明文章出处:https://blog.brain1981.com/942.html。百度和各类采集站皆不可信,搜索请谨慎鉴别。技术类文章一般都有时效性,本人习惯不定期对自己的博文进行修正和更新,因此请访问出处以查看本文的最新版本。

关注我们的微信公众号-JennyStudio 本站记录了近几年的工作中遇到的一些技术问题和解决过程,“作品集”还收录了本人的大部分作品展示。除了本博客外,我们的工作室网站 – JennyStudio,内有更多作品回顾和展示。
您也可以扫描左边的二维码,关注我们的微信公众号,在微信上查看我们的案例。

4 关于 “WordPress后台定制-在自定义字段面板中调用媒体/图片上传对话框” 的评论

      1. ArtTag

        感谢解答!受教了!!我去研究一下。另外还有个问题,这个上传的文件地址如何通过数据标签在前端页面调用呢?

        回复

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注