建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

WordPress网站前端投稿实现图片上传功能

GG网络技术分享 2025-03-18 16:16 0


使用WordPress做网站时,需要使用前端投稿功能,我们可以在前端投稿功能中添加图片上传功能。这样用户在前端就可以直接上传图片了。

下面学建站网介绍一下怎么在WordPress网站前端投稿实现图片上传功能。这里是采用直接调用wordpress媒体中心上传功能来实现的。

方法很简单,只要在前端投稿页面,需要上传图片位置,添加以下的代码即可。

<style>
.imgup .custom_media_url{padding:0 10px;border:1px solid #ddd;height:40px;line-height:40px;width:240px;}
.imgup .custom_media_upload{padding:0 10px;border:1px solid #ddd;background:#f60;height:40px;line-height:40px;width:100px;text-align:center}
</style>
<div class="imgup">
<img class="custom_media_image" src="" style="width:60px; height:60px" /><br>
<input class="custom_media_url" type="text" name="gslogo" value="">
<input type="button" value="上传图片" 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>
</div>

通过这个代码后,点击上传按钮,就用上了最新的媒体管理工具,并且可以直接上传到媒体库了。

如果需要注册的普通用户可以上传图片,可以在functions.php文件里给订阅者添加上传权限。

function dahuzi_add_user_rights() {
$role = 'subscriber';
$role = get_role($role);
$role->add_cap('upload_files');
}
add_action( 'admin_init', 'dahuzi_add_user_rights');

如果要去除订阅者的上传权限功能,可以放以下的代码:

function dahuzi_add_user_rights() {
$role = 'subscriber';
$role = get_role($role);
$role->remove_cap('upload_files');
}
add_action( 'admin_init', 'dahuzi_add_user_rights');

标签:

提交需求或反馈

Demand feedback