![]()
该文章功能依托于《Simple Local Avatars》插件运行,请先安装插件。
插件安装完成后,添加功能代码!
以Puock主题为列,找到用户中心页面模板。
wordpress-theme-puock/inc/classes/PuockUserCenter.php
在register_basic_menus中添加以下代码
self::$menus['avatars'] = [
'title' => __('修改头像', PUOCK),
'subtitle' => __('自定义上传头像', PUOCK),
'call' => array(__CLASS__, 'ailcc_avatars'),
];
然后再在下方添加以下代码即可。
public static function ailcc_avatars()
{
wp_enqueue_script( 'jcrop', '/wp-includes/js/jcrop/jquery.Jcrop.min.js', array( 'jquery' ), '0.9.13', true );
wp_enqueue_style( 'jcrop', '/wp-includes/js/jcrop/jquery.Jcrop.min.css', array(), '0.9.13' );
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
?>
<div class="block-content">
<div class="entry-content">
<h3>修改头像</h3>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">当前头像</label>
<div class="col-sm-10">
<?php echo wp_kses_post( get_simple_local_avatar( $current_user->ID ) ); ?>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">上传头像</label>
<div class="col-sm-10">
<form id="avatar-form" method="post" enctype="multipart/form-data">
<input type="file" name="simple-local-avatar" id="simple-local-avatar" class="form-control mb-3">
<input type="hidden" name="action" value="simple_local_avatar_upload" />
<small class="c-sub">图片上传时,可以对图片进行自由裁剪!<br />上传图像后会清空此前头像,请谨慎操作。</small>
<?php wp_nonce_field( 'simple_local_avatar_nonce', '_simple_local_avatar_nonce', false ); ?>
<div id="avatar-preview" style="margin-top: 15px;"></div>
<input type="hidden" name="x">
<input type="hidden" name="y">
<input type="hidden" name="width">
<input type="hidden" name="height">
<input type="submit" id="uploadBtn" value="更新头像" class="btn btn-sm btn-primary" style="display: none;margin-top: 15px;">
</form>
<?php if (get_user_meta($current_user->ID, 'simple_local_avatar', true)) : ?>
<form id="delete-avatar-form" method="post">
<input type="submit" id="deleteBtn" value="删除头像" class="btn btn-sm btn-danger" style="margin-top: 15px;" <?php echo empty( $current_user->simple_local_avatar ) ? ' style="display:none;"' : ''; ?>>
</form>
<?php endif; ?>
</div>
</div>
<script>
jQuery(function($) {
var preview = $('#avatar-preview'); // 预览区域
var input = $('#simple-local-avatar'); // 上传字段
input.on('change', function() { // 初始化Jcrop
var file = this.files[0];
if (file) {
var allowedTypes = ['image/jpeg', 'image/png'];
if (!allowedTypes.includes(file.type)) {
window.Puock.toast('请选择 JPG 或 PNG 文件', TYPE_DANGER);
$(this).val(''); // 清空非允许文件
preview.empty();
return;
}
var img = new Image(); // 创建一个新的图片对象
img.onload = function() {
var actualW = img.width;
var actualH = img.height;
if (actualW < 92 || actualH < 92) {
layer.msg('头像长宽尺寸不能小于92像素', {icon: 5});
window.setTimeout(function () {
window.location.reload();
},500)
} else {
$('#uploadBtn').show();
preview.empty().append(img);// 将图片添加到预览区域中
$(img).Jcrop({ // 初始化Jcrop
aspectRatio: 1,
onSelect: function(c) { // 更新隐藏字段的值
if(c.w < 92 || c.h < 92){
layer.msg('裁剪头像尺寸不能小于92x92像素', {icon: 5});
} else {
var jcropX = c.x; // 获取 jcrop 裁剪后的坐标
var jcropY = c.y;
var jcropW = c.w;
var jcropH = c.h;
console.log('jcrop 裁剪后的坐标:(' + jcropX + ', ' + jcropY + ', ' + jcropW + ', ' + jcropH + ')');
var wpX = Math.round(jcropX * actualW / $(img).width()); // 计算 jcrop 裁剪后的坐标在 WordPress 编辑器中的坐标
var wpY = Math.round(jcropY * actualH / $(img).height());
var wpW = Math.round(jcropW * actualW / $(img).width());
var wpH = Math.round(jcropH * actualH / $(img).height());
console.log('WordPress 编辑器的坐标:(' + wpX + ', ' + wpY + ', ' + wpW + ', ' + wpH + ')');
console.log('图片的尺寸:(' + actualW + ', ' + actualH + ')');
$('input[name="x"]').val(wpX); // 更新隐藏字段的值
$('input[name="y"]').val(wpY);
$('input[name="width"]').val(wpW);
$('input[name="height"]').val(wpH);
}
}
});
}
};
var reader = new FileReader(); // 加载图片
reader.onload = function(e) {
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
$('#delete-avatar-form').on('submit', function(e) {
e.preventDefault();
var userId = <?php echo json_encode($current_user->ID); ?>;
var nonce = '<?php echo wp_create_nonce( 'remove_simple_local_avatar_nonce' );?>';
$.post('<?php echo admin_url('admin-ajax.php'); ?>?action=remove_simple_local_avatar&user_id=' + userId + '&_wpnonce=' + nonce, function(response) {
var avatarUrl = $(response).attr('src');
console.log(response);
if (avatarUrl) {
console.log("删除成功头像,新头像地址为:" + avatarUrl);
window.Puock.toast('头像删除成功', TYPE_SUCCESS);
setTimeout(function() {
window.location.reload();
}, 1000);
} else {
window.Puock.toast('头像删除失败', TYPE_DANGER);
setTimeout(function() {
window.location.reload();
}, 1000);
}
});
});
});
</script>
<?php
if(!empty( $_FILES['simple-local-avatar']['name'] )) {
if ( isset( $_POST['action'] ) && 'simple_local_avatar_upload' == $_POST['action'] ) {
if ( ! wp_verify_nonce( $_POST['_simple_local_avatar_nonce'], 'simple_local_avatar_nonce' ) ) {
die( 'Security check' );
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$upload_dir = wp_upload_dir();
$filename = $_FILES['simple-local-avatar']['name'];
$tmp_name = $_FILES['simple-local-avatar']['tmp_name'];
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$allowed_mime = array('image/jpeg', 'image/png');
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $tmp_name);
finfo_close($finfo);
if (!in_array($mime, $allowed_mime)) {
echo '<div class="alert alert-success">只允许上传 JPG 或 PNG 文件!</div>'; exit;
}
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new_filename = uniqid($user_id.'-', true) . '.' . $extension;
$user_folder = $upload_dir['basedir'] . '/avatars/' . $user_id;
if ( ! file_exists( $user_folder ) ) { //检测目录 存在则创建
wp_mkdir_p( $user_folder );
}
$existing_files = glob( $user_folder . '/*' ); // 清空旧头像文件
foreach ( $existing_files as $file ) {
if ( is_file( $file ) ) {
unlink( $file );
}
}
$file_path = $user_folder . '/' . $new_filename;
if ( ! @move_uploaded_file( $tmp_name, $file_path ) ) {
echo '<div class="alert alert-success">头像上传失败,无法移动临时文件,请检查 uploads/avatars 文件夹权限 (755)!</div>'; exit;
}
// 裁剪图像
$jcropW = intval($_POST['width']);
$jcropH = intval($_POST['height']);
$jcropX = intval($_POST['x']);
$jcropY = intval($_POST['y']);
$image = wp_get_image_editor($file_path);
if ( is_wp_error( $image ) ) {
wp_die( '图像处理失败:' . $image->get_error_message() );
echo '<div class="alert alert-success">图像处理失败:'. $image->get_error_message() .'!</div>'; exit;
} else {
$image->crop($jcropX, $jcropY, $jcropW, $jcropH);
$image->save($file_path);
}
// 更新用户meta头像信息
$meta_value['blog_id'] = get_current_blog_id();
$meta_value['full'] = $upload_dir['baseurl'] . '/avatars/' . $user_id . '/' . $new_filename;
if ( $file_path && file_exists( $file_path ) ) {
update_user_meta( $current_user->ID, 'simple_local_avatar', $meta_value );
update_user_meta( $current_user->ID, 'simple_local_avatar_rating', 'G' );
?>
<script>window.location.href=window.location.href;</script>
<?php
} else {
echo '<div class="alert alert-success">头像保存失败,请重试。</div>'; exit;
}
}
}
}
}
以下代码可以删除,上传时已经随机生成文件名。
考虑到wordpress图片上传不会重命名的情况,假如图片名称中有中文,不确定能否正常引用,所以建议将图片名称重命名。
在主题的functions.php文件尾部加入以下代码即可自动重命名。
function custom_upload_filter( $file ){
$info = pathinfo($file['name']);
$ext = $info['extension'];
$filedate = date('YmdHis').rand(10,99);//为了避免时间重复,再加一段2位的随机数
$file['name'] = $filedate.'.'.$ext;
return $file;
}
add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
共计45人点赞,其中9人来自小程序
正文完
微信扫码打开小程序体验更多功能


