建站教程

建站教程

Products

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

WordPress在评论框添加QQ获取用户名、邮箱、头像(WordPress主题开发中使用Ajax异步更新前端用户头像)

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


WordPress在评论框添加QQ获取用户名、邮箱、头像

国内QQ比较流行,在评论框添加QQ并获取用户名头像等非常方便用户使用。

如何实现这个功能呢?下边就来看这个步骤吧:

先把一下的代码添加到主题的 function.php

//添加QQ号码字段

add_action('wp_insert_comment','inlojv_sql_insert_qq_field',10,2);

function inlojv_sql_insert_qq_field($comment_ID,$commmentdata) {

$qq = isset($_POST['new_field_qq']) ? $_POST['new_field_qq'] : false;

update_comment_meta($comment_ID,'new_field_qq',$qq); // new_field_qq 是表单name值,也是存储在数据库里的字段名字

}

// 后台评论中显示qq字段

add_filter( 'manage_edit-comments_columns', 'add_comments_columns' );

add_action( 'manage_comments_custom_column', 'output_comments_qq_columns', 10, 2 );

function add_comments_columns( $columns ){

$columns[ 'new_field_qq' ] = __( 'QQ号' ); // 新增列名称

return $columns;

}

function output_comments_qq_columns( $column_name, $comment_id ){

switch( $column_name ) {

case "new_field_qq" :

// 这是输出值,可以拿来在前端输出,这里已经在钩子manage_comments_custom_column上输出了

echo get_comment_meta( $comment_id, 'new_field_qq', true );

break;

}

}

 

//留言板获取QQ头像

add_filter( 'get_avatar', 'inlojv_change_avatar', 10, 3 );

function inlojv_change_avatar($avatar){

global $comment;

if( get_comment_meta( $comment->comment_ID, 'new_field_qq', true ) ){

$qq_number = get_comment_meta( $comment->comment_ID, 'new_field_qq', true );

$qqavatar = file_get_contents('http://ptlogin2.qq.com/getface?appid=1006102&imgtype=3&uin='.$qq_number);

preg_match('/https:(.*?)&t/',$qqavatar,$m); // 匹配 http: 和 &t 之间的字符串

return '<img src="'.stripslashes($m[1]).'" class="avatar avatar-40 photo" alt="qq_avatar" />';

}else{

return $avatar ;

}

}

下载get_qqinfo.php的文件保存到当前主题的modules文件夹内,作为获取API的文件。

关注 私信

把下面的代码放到主题的JS文件里,可以是commen.js也 可以是main.js。

// 初始化

$(function(){

inlojv_js_getqqinfo();

});

// 设置cookie

function setCookie(a,c){var b=30;var d=new Date();d.setTime(d.getTime()+b*24*60*60*1000);document.cookie=a+"="+escape(c)+";expires="+d.toGMTString()}

// 获取cookie

function getCookie(b){var a,c=new RegExp("(^| )"+b+"=([^;]*)(;|$)");if(a=document.cookie.match(c)){return unescape(a[2])}else{return null}}

// 核心函数

function inlojv_js_getqqinfo(){

// 获取cookie

if(getCookie('user_avatar') && getCookie('user_qq') ){

//$('.comt-title img').attr('src',getCookie('user_avatar'));

$('#comt-qq').val(getCookie('user_qq')); //获取缓存QQ号

}

$('#comt-qq').on('blur',function(){

var qq=$('#comt-qq').val(); // 获取访客填在qq表单上的qq数字,其中#comt-qq表示QQ input标签上的id!

$('#email').val($.trim(qq)+'@qq.com'); // 将获取到的qq,改成qq邮箱填入邮箱表单,其中#email表示邮箱input标签上的id

// ajax方法获取昵称

$.ajax({

type: 'get',

url:jsui.uri+'/modules/get_qqinfo.php?type=getqqnickname&qq='+qq, //get_qqinfo所在位置,用于获取QQ信息

dataType: 'jsonp',

jsonp: 'callback',

jsonpCallback: 'portraitCallBack',

success: function(data) {

// console.log(data);

$('#author').val(data[qq][6]); // 将返回的qq昵称填入到昵称input表单上

setCookie('user_qq',qq); // 设置cookie

},

error: function() {

$('#comt-qq,#author,#email').val(''); // 获取失败清空表单

}

});

// 获取头像

$.ajax({

type: 'get',

url:jsui.uri+'/modules/get_qqinfo.php?type=getqqavatar&qq='+qq, //get_qqinfo所在位置,用户获取QQ头像信息

dataType: 'jsonp',

jsonp: 'callback',

jsonpCallback: 'qqavatarCallBack',

success: function(data) {

$('.comt-title img').attr('src',data[qq]); // 将返回的qq头像设置到你评论表单区域显示头像的节点上

setCookie('user_avatar',data[qq]); // 设置cookie

},

error: function() {

$('#comt-qq,#author,#email').val(''); // 获取失败清空表单

}

});

});

}

然后刷新文章页面,评论框此时可以获取QQ头像了。

WordPress主题开发中使用Ajax异步更新前端用户头像

html代码如下:

<div class=\\\"file\\\">   <span>上传头像</span>   <input type=\\\"file\\\" name=\\\"addPic\\\" class=\\\"addPic\\\" style=\\\"\\\" id=\\\"addPic\\\" accept=\\\".jpg, .gif, .png\\\" resetonclick=\\\"true\\\" data-nonce=\\\"<?php echo $wp_create_nonce; ?>\\\"></div>//其中<?php $wp_create_nonce = wp_create_nonce(\\\'wpshequ-\\\'.get_current_user_id());?>

js(使用了JS中的FormData)代码如下:

<script type=\\\"text/javascript\\\">  $(\\\"#addPic\\\").change(function(e){    var _this = $(this)    var nonce = _this.data(\\\"nonce\\\")    var file = e.currentTarget.files[0];    console.log(file)    //结合formData实现图片预览    var sendData=new FormData();    sendData.append(\\\'nonce\\\',nonce);    sendData.append(\\\'action\\\',\\\'update_avatar_photo\\\');    sendData.append(\\\'file\\\',file);        $.ajax({      url: \\\"/wp-admin/admin-ajax.php\\\",      type: \\\'POST\\\',      cache: false,      data: sendData,      processData: false,      contentType: false    }).done(function(res) {      if (res.status == 1) {        layer.msg(res.msg, function(){ location.reload(); });        setTimeout(function(){location.reload()},1000)      }else{        layer.msg(res.msg, function(){ location.reload(); });      }    }).fail(function(res) {        layer.msg(\\\'网络错误\\\', function(){ location.reload(); });    });  });</script>//其中的弹窗提示使用了layer.js

php后端处理代码如下:

// 上传头像avatar_photofunction mx_update_avatar_photo(){    header(\\\'Content-type:application/json; Charset=utf-8\\\');    global $current_user;    $uid = $current_user->ID;    $nonce   = !empty($_POST[\\\'nonce\\\']) ? $_POST[\\\'nonce\\\'] : null;    $file = !empty($_FILES[\\\'file\\\']) ? $_FILES[\\\'file\\\'] : null;    if ($nonce && !wp_verify_nonce($nonce, \\\'wpshequ-\\\' . $uid)) {        echo json_encode(array(\\\'status\\\' => \\\'0\\\', \\\'msg\\\' => \\\'非法请求\\\'));exit;    }    $file_index = mb_strrpos($file[\\\"name\\\"],\\\'.\\\'); //扩展名定位    //图片验证    $is_img = getimagesize($file[\\\"tmp_name\\\"]);        if(!$is_img && true){        echo json_encode(array(\\\'status\\\' => \\\'0\\\', \\\'msg\\\' => \\\'上传文件类型错误\\\'));exit;    }    //图片类型验证    $image_type = [\\\'image/jpg\\\', \\\'image/gif\\\', \\\'image/png\\\', \\\'image/bmp\\\', \\\'image/pjpeg\\\', \\\"image/jpeg\\\"];    if(!in_array($file[\\\'type\\\'], $image_type) && true){        echo json_encode(array(\\\'status\\\' => \\\'0\\\', \\\'msg\\\' => \\\'禁止上传非图片类型文件\\\'));exit;    }    //图片后缀验证    $postfix = [\\\'.png\\\',\\\'.jpg\\\',\\\'.jpeg\\\',\\\'pjpeg\\\',\\\'gif\\\',\\\'bmp\\\'];    $file_postfix = strtolower(mb_substr($file[\\\"name\\\"], $file_index));    if(!in_array($file_postfix, $postfix) && true){        echo json_encode(array(\\\'status\\\' => \\\'0\\\', \\\'msg\\\' => \\\'上传后缀不允许\\\'));exit;    }    if ( !empty( $file ) ) {        // 获取上传目录信息        $wp_upload_dir = wp_upload_dir();        // 将上传的图片文件移动到上传目录 md5纯命名图片        $info = pathinfo($file[\\\'name\\\']);        $ext  = empty($info[\\\'extension\\\']) ? \\\'\\\' : \\\'.\\\' . $info[\\\'extension\\\'];        $name = basename($file[\\\'name\\\'], $ext);        $basename = time().\\\'-\\\'.substr(md5($name), 0, 15) . $ext;        //        $filename   = $wp_upload_dir[\\\'path\\\'] . \\\'/\\\' . $basename;        $re         = rename( $file[\\\'tmp_name\\\'], $filename );        $attachment = array(            \\\'guid\\\'           => $wp_upload_dir[\\\'url\\\'] . \\\'/\\\' . $basename,            \\\'post_mime_type\\\' => $file[\\\'type\\\'],            \\\'post_title\\\'     => preg_replace( \\\'/\\\\.[^.]+$/\\\', \\\'\\\', $basename ),            \\\'post_content\\\'   => \\\'\\\',            \\\'post_status\\\'    => \\\'inherit\\\'        );        $attach_id  = wp_insert_attachment( $attachment, $filename );        require_once( ABSPATH . \\\'wp-admin/includes/image.php\\\' );        $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );        wp_update_attachment_metadata( $attach_id, $attach_data );        if($attach_id){            update_user_meta($uid, \\\'wp_user_avatar\\\', $attach_id);            echo json_encode(array(\\\'status\\\' => \\\'1\\\', \\\'msg\\\' => \\\'上传成功\\\'));exit;        } else {            echo json_encode(array(\\\'status\\\' => \\\'0\\\', \\\'msg\\\' => \\\'上传失败\\\'));exit;        }    }    echo json_encode(array(\\\'status\\\' => \\\'0\\\', \\\'msg\\\' => \\\'文件错误\\\'));exit;}add_action(\\\'wp_ajax_mx_update_avatar_photo\\\', \\\'mx_update_avatar_photo\\\');add_action(\\\'wp_ajax_nopriv_mx_update_avatar_photo\\\', \\\'mx_update_avatar_photo\\\');

标签:

提交需求或反馈

Demand feedback