wordpress调用自带媒体中心图片上传功能
网站文章 2026-09-21 06:49:12 4 0

wordpress自带的媒体中心具有便捷的附件或图片上传功能,而在制作主题或插件时往往会需要用到上传功能,比如上传LOGO、上传照片或投稿时上传附件等,如果自己编写上传功能不仅麻烦且浪费时间,而wordpress早就已经考虑到了这一些问题,因此集成了相关的一些函数提供给开发者,以便节省开发的时间成本,下面博客吧分享一下如何调用wordpress自带的图片上传功能。

注意:确认调用的页面已经引入jquery库,否则无效!

该方法适用于wordpress 3.6以上版本:

1、在要调用wordpress图片上传功能的页面添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php wp_enqueue_media();?>
<script>   
jQuery(document).ready(function(){   
    var upload_frame;   
    var value_id;   
    jQuery('.upload_button').live('click',function(event){   
        value_id =jQuery( this ).attr('id');       
        event.preventDefault();   
        if( upload_frame ){   
            upload_frame.open();   
            return;   
        }   
        upload_frame = wp.media({   
            title: 'Insert image',   
            button: {   
                text: 'Insert',   
            },   
            multiple: false   
        });   
        upload_frame.on('select',function(){   
            attachment = upload_frame.state().get('selection').first().toJSON();   
            jQuery('input[name='+value_id+']').val(attachment.url);   
        });    
        upload_frame.open();   
    });   
});   
</script>

2、在需要添加图片上传的地方添加以下代码:

1
2
<input type="text" size="60" value="" name="upload" id="upload_input"/>
<a id="upload" class="upload_button button" href="#">上传</a>

添加完成后,上传效果如下:

该方法适用于wordpress 3.6之前的版本:

1、在要调用wordpress图片上传功能的页面添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php 
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
    wp_enqueue_script('my-upload');
    wp_enqueue_style('thickbox'); 
?>
<script>
jQuery(document).ready(function() {
    jQuery('#upload_image_button').click(function() {
     formfield = jQuery('#upload_image').attr('name');
     // show WordPress' uploader modal box
     tb_show('', '<?php echo admin_url(); ?>media-upload.php?type=image&amp;TB_iframe=true');
     return false;
    });
    window.send_to_editor = function(html) {
     // this will execute automatically when a image uploaded and then clicked to 'insert to post' button
     imgurl = jQuery('img',html).attr('src');
     // put uploaded image's url to #upload_image
     jQuery('#upload_image').val(imgurl);
     tb_remove();
    }
});
</script>

2、在需要添加图片上传的地方添加以下代码:

1
2
<input name="pic" id="upload_image" type="text" value="" />
<input id="upload_image_button" type="button" value="上传图片" />

添加完成后,上传效果如下:

温馨提示:不要随便开发上传功能给网站用户,避免用户上传一些不安全的东西!

文章说明
本文标签:
©版权声明
本站提供的一切软件、教程和游戏辅助仅限用于娱乐和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络收集,版权争议与本站无关。如有侵权请邮件与我们联系处理。敬请谅解!6594404@qq.com