Blog / WordPress/ Implementing QQ Avatar and Nickname Auto-Fetch in WordPress Comments

Implementing QQ Avatar and Nickname Auto-Fetch in WordPress Comments

WordPress评论框输入QQ一键获取头像和昵称

Overview

Many WordPress blogs feature a comment form that can automatically fetch a user's nickname and avatar when they enter their QQ number. While numerous tutorials exist, some are outdated or contain errors. This article provides a consolidated and corrected implementation.

QQ Avatar and Nickname Fetch Demo

How It Works

The functionality has three main parts: adding a QQ field to the comment form and storing it in the database; using frontend JavaScript to call backend APIs for real-time nickname and avatar retrieval; and displaying the QQ avatar in the comment list and admin panel instead of the default Gravatar.

Important Note: The external APIs referenced may be unstable or deprecated. Direct frontend calls to third-party services pose security and reliability risks. Use this guide for learning purposes and evaluate carefully before deploying in production.

Step 1: Add and Store the QQ Field

First, add a QQ number input field to your theme's comment form template (usually comments.php).

<p class="comment-form-qq">
    <label for="qq">QQ Number</label>
    <input id="comment-qq" name="new_field_qq" type="text" value="" placeholder="Optional" />
</p>

Set the name attribute to new_field_qq for consistency with the backend code.

Next, add this code to your theme's functions.php to save the QQ number to the comment metadata and display it in the admin comments list.

// Save QQ field to database
add_action('wp_insert_comment', 'save_comment_qq_field', 10, 2);
function save_comment_qq_field($comment_id, $commentdata) {
    if (isset($_POST['new_field_qq'])) {
        $qq = sanitize_text_field($_POST['new_field_qq']);
        update_comment_meta($comment_id, 'new_field_qq', $qq);
    }
}

// Display QQ field in admin comments list
add_filter('manage_edit-comments_columns', 'add_qq_column_to_comments');
function add_qq_column_to_comments($columns) {
    $columns['new_field_qq'] = __('QQ Number');
    return $columns;
}
add_action('manage_comments_custom_column', 'display_qq_in_comments_column', 10, 2);
function display_qq_in_comments_column($column, $comment_id) {
    if ($column === 'new_field_qq') {
        echo get_comment_meta($comment_id, 'new_field_qq', true);
    }
}

Step 2: Real-time QQ Info Fetch (Frontend)

When a user enters a QQ number and leaves the field (blur event), JavaScript uses AJAX to call backend endpoints, populating the nickname and avatar fields. Cookies store the info for page refreshes.

Critical: The third-party APIs (qzone.qq.com, ptlogin2.qq.com) may change or block external calls. The example code contains hardcoded local paths (127.0.0.1)—you must update these to match your environment.

Frontend JavaScript (requires jQuery):

jQuery(document).ready(function($) {
    // On page load, try to fill from cookies
    var savedQQ = getCookie('user_qq');
    var savedAvatar = getCookie('user_avatar');
    if (savedQQ && savedAvatar) {
        $('#comment-qq').val(savedQQ);
        $('.comment-avatar-preview img').attr('src', savedAvatar);
    }

    $('#comment-qq').on('blur', function() {
        var qq = $(this).val().trim();
        if (!qq || !/^[1-9]d{4,11}$/.test(qq)) return;

        // Auto-fill email field (adjust ID as needed)
        $('#comment-email').val(qq + '@qq.com');

        // Fetch nickname
        $.ajax({
            type: 'GET',
            url: '/wp-content/themes/your-theme/func_getqqinfo.php?type=getqqnickname&qq=' + qq,
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'portraitCallBack',
            success: function(data) {
                if (data && data[qq]) {
                    $('#comment-author').val(data[qq][6]); // Adjust selector
                    setCookie('user_qq', qq, 7);
                }
            },
            error: function() { console.error('Nickname fetch failed'); }
        });

        // Fetch avatar
        $.ajax({
            type: 'GET',
            url: '/wp-content/themes/your-theme/func_getqqinfo.php?type=getqqavatar&qq=' + qq,
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'qqavatarCallBack',
            success: function(data) {
                if (data && data[qq]) {
                    var avatarUrl = data[qq];
                    $('.comment-avatar-preview img').attr('src', avatarUrl);
                    setCookie('user_avatar', avatarUrl, 7);
                }
            },
            error: function() { console.error('Avatar fetch failed'); }
        });
    });
});

// Cookie helper functions
function setCookie(name, value, days) {
    var d = new Date();
    d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = name + "=" + encodeURIComponent(value) + ";" + expires + ";path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}

Backend PHP handler (func_getqqinfo.php):

<?php
header("Content-Type: application/json; charset=UTF-8");
$type = isset($_GET['type']) ? $_GET['type'] : '';
$qq = isset($_GET['qq']) ? trim($_GET['qq']) : '';

if (!preg_match('/^[1-9]d{4,11}$/', $qq)) {
    echo json_encode(array('error' => 'Invalid QQ number'));
    exit;
}

if ($type == 'getqqnickname') {
    $apiUrl = 'http://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=' . $qq;
    $response = @file_get_contents($apiUrl);
    if ($response !== false) {
        $response = mb_convert_encoding($response, 'UTF-8', 'GBK');
        $callback = isset($_GET['callback']) ? $_GET['callback'] : 'portraitCallBack';
        echo $callback . '(' . $response . ')';
    } else {
        echo json_encode(array('error' => 'Failed to fetch nickname'));
    }
} elseif ($type == 'getqqavatar') {
    $apiUrl = 'http://ptlogin2.qq.com/getface?appid=1006102&imgtype=3&uin=' . $qq;
    $response = @file_get_contents($apiUrl);
    if ($response !== false) {
        $response = str_replace("pt.setHeader", "qqavatarCallBack", $response);
        echo $response;
    } else {
        echo json_encode(array('error' => 'Failed to fetch avatar'));
    }
} else {
    echo json_encode(array('error' => 'Invalid request type'));
}
?>

Step 3: Display QQ Avatar in Comments

Use the get_avatar filter to replace Gravatar with the QQ avatar when a comment has a stored QQ number. Add to functions.php:

// Replace comment avatar with QQ avatar
add_filter('get_avatar', 'replace_gravatar_with_qq_avatar', 10, 3);
function replace_gravatar_with_qq_avatar($avatar, $id_or_email, $args) {
    $comment = null;
    if (is_object($id_or_email) && isset($id_or_email->comment_ID)) {
        $comment = $id_or_email;
    } elseif (is_numeric($id_or_email)) {
        $comment = get_comment($id_or_email);
    }
    if ($comment) {
        $qq_number = get_comment_meta($comment->comment_ID, 'new_field_qq', true);
        if (!empty($qq_number)) {
            $apiResponse = @file_get_contents('http://ptlogin2.qq.com/getface?appid=1006102&imgtype=3&uin=' . $qq_number);
            if ($apiResponse && preg_match('/http:(.*?)&t/', $apiResponse, $matches)) {
                $qq_avatar_url = 'http:' . stripslashes($matches[1]);
                $avatar = sprintf(
                    '<img src="%s" class="%s" width="%d" height="%d" alt="%s" />',
                    esc_url($qq_avatar_url),
                    esc_attr($args['class']),
                    $args['width'],
                    $args['height'],
                    esc_attr__('QQ Avatar')
                );
            }
        }
    }
    return $avatar;
}

Considerations and Recommendations

  • API Stability: The Tencent APIs used are not official public endpoints and may fail or be restricted.
  • Security: Always validate and sanitize user input. Use sanitize_text_field and proper regex checks as shown.
  • Performance: Remote API calls on each page load can slow your site. Consider implementing a local cache.
  • User Experience: Replace basic alert() prompts with non-blocking UI notifications and loading indicators.
  • Alternatives: For a stable solution, consider other avatar services or encourage users to use Gravatar.

This is the complete process for implementing QQ-based avatar and nickname fetching in WordPress comments. Adjust selectors, paths, and details according to your theme. Thoroughly test before deployment due to external dependencies.

Post a Comment

Your email will not be published. Required fields are marked with *.