WordPress用户中心修改用户头像简单教程!

6,565次阅读
12条评论

WordPress用户中心修改用户头像简单教程!

该文章功能依托于《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' );
沛霖主页 不想说话 mp_wx_efd60d3703 mp_wx_1c9728368b mp_wx_9dc2a13583 mp_wx_a694faf314 mp_wx_589f50e09b mp_wx_6a98a928c4 mp_wx_137e03e409

共计45人点赞,其中9人来自小程序

正文完
微信扫码打开小程序体验更多功能
post-qrcode
 45
沛霖主页
版权声明:本站原创文章,由 沛霖主页 2023-04-12发表,共计7616字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(12条评论)
monfly 评论达人 LV.1
2025-10-28 12:52:22 回复

现在是上传图片后就没有反应了,没有弹出像这样的编辑,没有更新按钮,不知道怎么回事 :beer:

 Android  Chrome  中国四川省遂宁市电信
    沛霖主页 博主
    2025-10-28 13:34:49 回复

    @monfly 有没装Simple Local Avatars?插件是依托于这个运行的,再就是新版的WordPress我没做支持,因为我没升级版本,所以就没弄,你看看F12里有什么报错,加我QQ,我教你怎么修改。66257875

     iPhone  Ailcc MiniProgram  中国上海上海市移动
      monfly 评论达人 LV.1
      2025-11-03 12:52:18 回复

      @沛霖主页 大佬,联系不上您,链接为https://****.***/***/***,如果需要管理员账号请提醒我 :beer:

       Android  Chrome  中国四川省遂宁市电信
amanda 评论达人 LV.1
2023-04-15 19:17:21 回复

:love: :love: :love:

 Windows  Edge  中国上海上海市电信
背靠背拥抱 评论达人 LV.1
2023-04-12 18:17:12 回复

有两把刷子,就是刷子毛不多!

 iPhone  Weixin  中国上海上海市电信
不想说话 评论达人 LV.1
2023-04-12 17:45:10 回复

支持大佬,沛霖哥哥最棒!!! :celebrate: :celebrate: :celebrate: :celebrate: :celebrate:

 Windows  Chrome  中国湖北省武汉市电信
lovau 评论达人 LV.1
2023-04-12 17:38:45 回复

干货满满!!!

 iPhone  Weixin  中国安徽省合肥市联通