本文详解如何为WordPress添加实时功能(实时评论、通知、协同编辑)。

什么是WebSocket

WebSocket(RFC 6455):

  • 全双工通信(Full-duplex)
  • 单个TCP连接(持久连接)
  • 低延迟(< 50ms)
  • 替代HTTP轮询(Polling)

vs HTTP轮询:

  • HTTP轮询:频繁发起HTTP请求(浪费资源)
  • WebSocket:建立连接后,服务端主动推送(高效)

为什么WordPress需要实时功能

传统WordPress(静态):

  • 评论需要刷新页面才能看到
  • 通知需要手动检查
  • 无协同编辑(多人同时编辑冲突)

实时WordPress:

  • 新评论实时显示(无需刷新)
  • 通知实时推送(类似Facebook)
  • 协同编辑(类似Google Docs)

实战一:搭建WebSocket服务器(Node.js)

安装依赖

# 创建项目目录

mkdir wp-realtime && cd wp-realtime

初始化Node.js项目

npm init -y

安装依赖

npm install ws express cors dotenv

安装开发依赖

npm install -D nodemon

创建WebSocket服务器

// server.js

const WebSocket = require('ws');

const express = require('express');

const cors = require('cors');

const http = require('http');

const app = express();

app.use(cors());

app.use(express.json());

// 创建HTTP服务器

const server = http.createServer(app);

// 创建WebSocket服务器

const wss = new WebSocket.Server({ server });

// 存储连接的客户端

const clients = new Map();

wss.on('connection', (ws, req) => {

console.log('新客户端连接');

// 分配客户端ID

const clientId = Date.now();

clients.set(ws, clientId);

// 接收消息

ws.on('message', (message) => {

const data = JSON.parse(message);

// 广播消息给所有客户端

clients.forEach((id, client) => {

if (client.readyState === WebSocket.OPEN) {

client.send(JSON.stringify({

type: 'new_comment',

postId: data.postId,

comment: data.comment,

author: data.author,

}));

}

});

});

// 连接关闭

ws.on('close', () => {

console.log('客户端断开连接');

clients.delete(ws);

});

});

// REST API:获取在线用户数

app.get('/api/online-users', (req, res) => {

res.json({ count: clients.size });

});

const PORT = process.env.PORT || 8080;

server.listen(PORT, () => {

console.log(`WebSocket服务器运行在端口 ${PORT}`);

});

启动服务器

# 开发模式(自动重载)

npx nodemon server.js

生产模式

node server.js

输出:

WebSocket服务器运行在端口 8080

实战二:WordPress集成WebSocket(实时评论)

前端JavaScript(主题文件)

后端PHP(接收WebSocket消息并保存到WordPress)

// 安装WP REST API扩展(允许WebSocket服务器调用)

add_action('rest_api_init', 'register_comment_endpoint');

function register_comment_endpoint() {

register_rest_route('wp/v2', '/add_comment', [

'methods' => 'POST',

'callback' => 'add_comment_callback',

'permission_callback' => '__return_true',

]);

}

function add_comment_callback($request) {

$params = $request->get_json_params();

$comment_id = wp_insert_comment([

'comment_post_ID' => $params['post_id'],

'comment_content' => $params['comment'],

'comment_author' => $params['author'],

'comment_approved' => 1,

]);

return rest_ensure_response(['comment_id' => $comment_id]);

}

实战三:实时通知(类似Facebook)

数据库设计(通知表)

-- 创建通知表

CREATE TABLE wp_notifications (

id BIGINT AUTO_INCREMENT PRIMARY KEY,

user_id BIGINT NOT NULL,

type VARCHAR(50) NOT NULL, -- 'comment', 'like', 'follow'

content TEXT NOT NULL,

link VARCHAR(255) NOT NULL,

is_read TINYINT DEFAULT 0,

created_at DATETIME DEFAULT CURRENT_TIMESTAMP

);

后端PHP(创建通知)

// 当有新评论时,创建通知

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

function create_notification($comment_id, $comment) {

$post = get_post($comment->comment_post_ID);

$post_author_id = $post->post_author;

global $wpdb;

$wpdb->insert('wp_notifications', [

'user_id' => $post_author_id,

'type' => 'comment',

'content' => $comment->comment_content,

'link' => get_permalink($post->ID) . '#comment-' . $comment_id,

'is_read' => 0,

'created_at' => current_time('mysql'),

]);

// 通过WebSocket推送通知

push_notification($post_author_id, [

'type' => 'new_notification',

'content' => $comment->comment_content,

'link' => get_permalink($post->ID),

]);

}

function push_notification($user_id, $data) {

// 调用Node.js WebSocket服务器API

$ch = curl_init('https://realtime.example.com:8080/push');

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([

'user_id' => $user_id,

'data' => $data,

]));

curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

curl_exec($ch);

curl_close($ch);

}

前端JavaScript(显示通知)

// 连接WebSocket(接收通知)

const ws = new WebSocket('wss://realtime.example.com:8080');

ws.onmessage = (event) => {

const data = JSON.parse(event.data);

if (data.type === 'new_notification') {

// 显示通知气泡

showNotification(data.content, data.link);

// 更新未读计数

updateUnreadCount();

}

};

function showNotification(content, link) {

// 桌面通知(浏览器权限)

if (Notification.permission === 'granted') {

new Notification('新通知', {

body: content,

icon: '/icon.png',

tag: link,

});

}

// 页面内通知(类似Facebook下拉)

$('#notification-dropdown').prepend(`

`);

}

实战四:协同编辑(类似Google Docs)

使用ShareDB(实时数据库同步)

# 安装ShareDB

npm install sharedb ws express

后端Node.js(ShareDB服务器)

// collaborative-server.js

const ShareDB = require('sharedb');

const WebSocket = require('ws');

const express = require('express');

const app = express();

const server = require('http').createServer(app);

const wss = new WebSocket.Server({ server });

const backend = new ShareDB();

const connection = backend.connect();

wss.on('connection', (ws) => {

const stream = WebSocketJSONStream(ws);

backend.listen(stream);

});

server.listen(8080, () => {

console.log('协同编辑服务器运行在端口 8080');

});

// 使用WebSocketJSONStream(需要安装)

// npm install @teamwork/websocket-json-stream

前端JavaScript(集成ShareDB到WordPress)

// 协同编辑(使用ShareDB)

import { Connection } from 'sharedb/lib/client';

const socket = new WebSocket('wss://realtime.example.com:8080');

const connection = new Connection(socket);

// 打开文档(按Post ID)

const doc = connection.get('posts', postId);

doc.subscribe((err) => {

if (err) throw err;

// 初始化内容

if (!doc.type) {

doc.create('text'); // 创建Text类型(支持协同编辑)

}

// 绑定到textarea

const textarea = document.getElementById('post-content');

textarea.value = doc.data;

// 监听本地修改

textarea.addEventListener('input', () => {

doc.submitOp([{ retain: textarea.value.length }]); // 简化示例

});

// 监听远程修改

doc.on('op', (op, source) => {

if (!source) {

textarea.value = doc.data; // 更新内容

}

});

});

实战五:部署WebSocket服务器(生产环境)

使用PM2(进程管理)

# 安装PM2

npm install -g pm2

启动WebSocket服务器

pm2 start server.js --name wp-realtime

查看状态

pm2 status

查看日志

pm2 logs wp-realtime

设置开机自启

pm2 startup

pm2 save

使用Nginx反向代理(WebSocket)

# /etc/nginx/sites-available/realtime.example.com

server {

listen 80;

server_name realtime.example.com;

location / {

proxy_pass http://localhost:8080;

proxy_http_version 1.1;

proxy_set_header Upgrade $http_upgrade;

proxy_set_header Connection "upgrade";

proxy_set_header Host $host;

# 超时设置(WebSocket长连接)

proxy_read_timeout 86400;

proxy_send_timeout 86400;

}

}

配置SSL(wss://)

# 使用Let's Encrypt

certbot --nginx -d realtime.example.com

自动配置HTTPS(Nginx插件)

WebSocket现在可以通过wss://访问(加密)

性能优化

优化一:使用Redis Pub/Sub(多服务器扩展)

// 使用Redis Pub/Sub(多服务器之间同步消息)

const redis = require('redis');

const publisher = redis.createClient();

const subscriber = redis.createClient();

// 订阅频道

subscriber.subscribe('wp_comments');

// 接收消息

subscriber.on('message', (channel, message) => {

// 广播给所有WebSocket客户端

wss.clients.forEach((client) => {

if (client.readyState === WebSocket.OPEN) {

client.send(message);

}

});

});

// 发布消息

function broadcast(message) {

publisher.publish('wp_comments', JSON.stringify(message));

}

优化二:使用SSE(Server-Sent Events,单向推送)

// SSE(简单场景:只需要服务端推送,不需要客户端发送)

app.get('/events', (req, res) => {

res.setHeader('Content-Type', 'text/event-stream');

res.setHeader('Cache-Control', 'no-cache');

res.setHeader('Connection', 'keep-alive');

// 每隔5秒推送一次

const intervalId = setInterval(() => {

res.write(`data: ${JSON.stringify({ time: new Date() })}\n\n`);

}, 5000);

// 客户端断开连接

req.on('close', () => {

clearInterval(intervalId);

});

});

// 前端JavaScript(SSE客户端)

const eventSource = new EventSource('/events');

eventSource.onmessage = (event) => {

const data = JSON.parse(event.data);

console.log('新数据:', data);

};

决策建议

| 场景 | 技术方案 | 理由 |

|------|----------|------|

| 实时评论 | WebSocket | 双向通信 |

| 实时通知 | WebSocket + SSE | 低延迟 |

| 协同编辑 | ShareDB + WebSocket | 冲突解决 |

| 股票/加密货币价格 | SSE | 单向推送足够 |

总结

WebSocket让WordPress拥有实时功能。2026年,实时用户体验已成为标准。

立即行动:用Node.js + WebSocket为你的WordPress添加实时评论功能!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。