文章目录[隐藏]
WordPress小批量定制插件与智能客服系统集成教程
引言:为什么需要集成智能客服系统?
在当今数字化的商业环境中,网站访客期望获得即时、个性化的支持体验。对于使用WordPress搭建的中小型企业网站来说,集成智能客服系统可以显著提升客户满意度,提高转化率,并减轻人工客服的工作负担。本教程将指导您如何开发一个WordPress定制插件,实现与小批量智能客服系统的无缝集成。
准备工作与环境配置
在开始开发之前,您需要准备以下环境:
- WordPress开发环境(本地或测试服务器)
- 代码编辑器(如VS Code、Sublime Text等)
- 智能客服系统的API密钥和接入文档
- 基础的PHP和JavaScript知识
第一步:创建插件基础结构
首先,在WordPress的wp-content/plugins目录下创建一个新文件夹,命名为smart-custom-chat-integration。在该文件夹中创建以下文件结构:
smart-custom-chat-integration/
├── smart-chat-integration.php # 主插件文件
├── includes/
│ ├── class-api-handler.php # API处理类
│ ├── class-settings-page.php # 设置页面类
│ └── class-frontend.php # 前端显示类
├── assets/
│ ├── css/
│ │ └── admin-style.css # 后台样式
│ └── js/
│ ├── admin-script.js # 后台脚本
│ └── frontend-script.js # 前端脚本
└── templates/
└── chat-widget.php # 聊天窗口模板
第二步:编写主插件文件
打开smart-chat-integration.php文件,添加以下代码:
<?php
/**
* Plugin Name: 智能客服系统集成
* Plugin URI: https://yourwebsite.com/
* Description: 将小批量智能客服系统集成到WordPress网站
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
* Text Domain: smart-chat-integration
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('SCI_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('SCI_PLUGIN_URL', plugin_dir_url(__FILE__));
define('SCI_VERSION', '1.0.0');
// 检查PHP版本
if (version_compare(PHP_VERSION, '7.0', '<')) {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>';
echo '智能客服插件需要PHP 7.0或更高版本。当前版本:' . PHP_VERSION;
echo '</p></div>';
});
return;
}
// 自动加载类文件
spl_autoload_register(function($class_name) {
$prefix = 'SCI_';
$base_dir = SCI_PLUGIN_PATH . 'includes/';
// 检查类是否属于本插件
$len = strlen($prefix);
if (strncmp($prefix, $class_name, $len) !== 0) {
return;
}
$relative_class = substr($class_name, $len);
$file = $base_dir . 'class-' . str_replace('_', '-', strtolower($relative_class)) . '.php';
if (file_exists($file)) {
require $file;
}
});
// 初始化插件
function sci_init_plugin() {
// 实例化核心类
$api_handler = new SCI_API_Handler();
$settings_page = new SCI_Settings_Page();
$frontend = new SCI_Frontend();
// 注册激活和停用钩子
register_activation_hook(__FILE__, ['SCI_Settings_Page', 'activate']);
register_deactivation_hook(__FILE__, ['SCI_Settings_Page', 'deactivate']);
}
add_action('plugins_loaded', 'sci_init_plugin');
第三步:创建API处理类
在includes/class-api-handler.php中,添加智能客服系统的API交互代码:
<?php
/**
* 智能客服API处理类
* 负责与智能客服系统进行通信
*/
class SCI_API_Handler {
private $api_key;
private $api_endpoint;
private $chat_enabled;
public function __construct() {
// 从数据库获取设置
$options = get_option('sci_settings');
$this->api_key = isset($options['api_key']) ? $options['api_key'] : '';
$this->api_endpoint = isset($options['api_endpoint']) ? $options['api_endpoint'] : 'https://api.smart-chat-system.com/v1';
$this->chat_enabled = isset($options['chat_enabled']) ? $options['chat_enabled'] : false;
// 添加AJAX处理钩子
add_action('wp_ajax_sci_send_message', [$this, 'handle_send_message']);
add_action('wp_ajax_nopriv_sci_send_message', [$this, 'handle_send_message']);
}
/**
* 发送消息到智能客服系统
* @param string $message 用户消息
* @param array $user_data 用户数据
* @return array API响应
*/
public function send_message($message, $user_data = []) {
// 检查API密钥是否设置
if (empty($this->api_key)) {
return [
'success' => false,
'error' => 'API密钥未配置'
];
}
// 准备请求数据
$request_data = [
'message' => sanitize_text_field($message),
'user_id' => isset($user_data['user_id']) ? $user_data['user_id'] : $this->generate_user_id(),
'user_info' => [
'name' => isset($user_data['name']) ? sanitize_text_field($user_data['name']) : '',
'email' => isset($user_data['email']) ? sanitize_email($user_data['email']) : '',
'page_url' => isset($_SERVER['HTTP_REFERER']) ? esc_url($_SERVER['HTTP_REFERER']) : ''
],
'timestamp' => current_time('timestamp')
];
// 发送HTTP请求到智能客服API
$response = wp_remote_post($this->api_endpoint . '/chat/message', [
'headers' => [
'Authorization' => 'Bearer ' . $this->api_key,
'Content-Type' => 'application/json'
],
'body' => json_encode($request_data),
'timeout' => 15
]);
// 处理响应
if (is_wp_error($response)) {
return [
'success' => false,
'error' => $response->get_error_message()
];
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
return [
'success' => true,
'data' => $data
];
}
/**
* 处理AJAX消息发送请求
*/
public function handle_send_message() {
// 验证nonce确保请求安全
if (!check_ajax_referer('sci_chat_nonce', 'nonce', false)) {
wp_die('安全验证失败', 403);
}
// 获取并清理用户输入
$message = isset($_POST['message']) ? sanitize_text_field($_POST['message']) : '';
$user_data = isset($_POST['user_data']) ? map_deep($_POST['user_data'], 'sanitize_text_field') : [];
if (empty($message)) {
wp_send_json_error(['error' => '消息不能为空']);
}
// 发送消息到智能客服系统
$result = $this->send_message($message, $user_data);
if ($result['success']) {
wp_send_json_success($result['data']);
} else {
wp_send_json_error(['error' => $result['error']]);
}
}
/**
* 生成唯一用户ID
* @return string 用户ID
*/
private function generate_user_id() {
if (isset($_COOKIE['sci_user_id'])) {
return $_COOKIE['sci_user_id'];
}
$user_id = 'user_' . wp_generate_uuid4();
setcookie('sci_user_id', $user_id, time() + (365 * 24 * 60 * 60), '/');
return $user_id;
}
/**
* 检查聊天功能是否启用
* @return bool
*/
public function is_chat_enabled() {
return $this->chat_enabled;
}
}
第四步:创建设置页面
在includes/class-settings-page.php中,创建插件设置页面:
<?php
/**
* 插件设置页面类
* 提供后台配置界面
*/
class SCI_Settings_Page {
public function __construct() {
add_action('admin_menu', [$this, 'add_admin_menu']);
add_action('admin_init', [$this, 'settings_init']);
add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_options_page(
'智能客服设置',
'智能客服',
'manage_options',
'smart-chat-integration',
[$this, 'settings_page_html']
);
}
/**
* 初始化设置
*/
public function settings_init() {
register_setting('sci_settings_group', 'sci_settings');
// 添加基本设置部分
add_settings_section(
'sci_basic_section',
'基本设置',
[$this, 'section_callback'],
'smart-chat-integration'
);
// API密钥字段
add_settings_field(
'api_key',
'API密钥',
[$this, 'api_key_field_render'],
'smart-chat-integration',
'sci_basic_section'
);
// API端点字段
add_settings_field(
'api_endpoint',
'API端点',
[$this, 'api_endpoint_field_render'],
'smart-chat-integration',
'sci_basic_section'
);
// 启用聊天字段
add_settings_field(
'chat_enabled',
'启用聊天功能',
[$this, 'chat_enabled_field_render'],
'smart-chat-integration',
'sci_basic_section'
);
// 聊天窗口位置
add_settings_field(
'chat_position',
'聊天窗口位置',
[$this, 'chat_position_field_render'],
'smart-chat-integration',
'sci_basic_section'
);
}
/**
* 渲染API密钥字段
*/
public function api_key_field_render() {
$options = get_option('sci_settings');
?>
<input type="password"
name="sci_settings[api_key]"
value="<?php echo isset($options['api_key']) ? esc_attr($options['api_key']) : ''; ?>"
class="regular-text">
<p class="description">从智能客服系统获取的API密钥</p>
<?php
}
/**
* 渲染API端点字段
*/
public function api_endpoint_field_render() {
$options = get_option('sci_settings');
?>
<input type="url"
name="sci_settings[api_endpoint]"
value="<?php echo isset($options['api_endpoint']) ? esc_attr($options['api_endpoint']) : 'https://api.smart-chat-system.com/v1'; ?>"
class="regular-text">
<p class="description">智能客服系统的API端点URL</p>
<?php
}
/**
* 渲染启用聊天字段
*/
public function chat_enabled_field_render() {
$options = get_option('sci_settings');
?>
<label>
<input type="checkbox"
name="sci_settings[chat_enabled]"
value="1"
<?php checked(isset($options['chat_enabled']) ? $options['chat_enabled'] : 0, 1); ?>>
启用智能客服聊天功能
</label>
<?php
}
/**
* 渲染聊天窗口位置字段
*/
public function chat_position_field_render() {
$options = get_option('sci_settings');
$position = isset($options['chat_position']) ? $options['chat_position'] : 'bottom-right';
?>
<select name="sci_settings[chat_position]">
<option value="bottom-right" <?php selected($position, 'bottom-right'); ?>>右下角</option>
<option value="bottom-left" <?php selected($position, 'bottom-left'); ?>>左下角</option>
<option value="top-right" <?php selected($position, 'top-right'); ?>>右上角</option>
<option value="top-left" <?php selected($position, 'top-left'); ?>>左上角</option>
</select>
<p class="description">选择聊天窗口在页面上的显示位置</p>
<?php
}
/**
* 设置页面HTML
*/
public function settings_page_html() {
if (!current_user_can('manage_options')) {
return;
}
?>
<div class="wrap">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<form action="options.php" method="post">
<?php
settings_fields('sci_settings_group');
do_settings_sections('smart-chat-integration');
submit_button('保存设置');
?>
</form>
<div class="sci-test-section">
<h2>API连接测试</h2>
<button id="sci-test-api" class="button button-secondary">测试API连接</button>
<div id="sci-test-result" style="margin-top: 10px;"></div>
</div>
</div>
<?php
}
/**
* 加载管理端资源
*/
public function enqueue_admin_assets($hook) {
if ($hook !== 'settings_page_smart-chat-integration') {
return;
}
wp_enqueue_style(
'sci-admin-style',
SCI_PLUGIN_URL . 'assets/css/admin-style.css',
[],
SCI_VERSION
);
wp_enqueue_script(
'sci-admin-script',
SCI_PLUGIN_URL . 'assets/js/admin-script.js',
['jquery'],
SCI_VERSION,
true
);
wp_localize_script('sci-admin-script', 'sci_admin', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('sci_admin_nonce')
]);
}
/**
* 插件激活时的操作
*/
public static function activate() {
// 设置默认选项
$default_options = [
'api_endpoint' => 'https://api.smart-chat-system.com/v1',
'chat_position' => 'bottom-right',
'chat_enabled' => true
];
if (!get_option('sci_settings')) {
add_option('sci_settings', $default_options);
}
// 创建必要的数据库表(如果需要)
// self::create_database_tables();
}
/**
* 插件停用时的操作
*/
public static function deactivate() {
// 清理临时数据
// 注意:这里通常不清除设置,以便重新激活时保留配置
}
}
第五步:创建前端显示类
在includes/class-frontend.php中,添加前端显示逻辑:
<?php
/**
* 前端显示类
* 处理聊天窗口的显示和交互
*/
class SCI_Frontend {
private $api_handler;
public function __construct() {
$this->api_handler = new SCI_API_Handler();
// 只在聊天启用时加载前端资源
if ($this->api_handler->is_chat_enabled()) {
add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_assets']);
add_action('wp_footer', [$this, 'render_chat_widget']);
}
}
/**
* 加载前端资源
*/
public function enqueue_frontend_assets() {
// 加载CSS样式
wp_enqueue_style(
'sci-chat-style',
SCI_PLUGIN_URL . 'assets/css/chat-style.css',
[],
SCI_VERSION
);
// 加载JavaScript
wp_enqueue_script(
'sci-chat-script',
SCI_PLUGIN_URL . 'assets/js/frontend-script.js',
['jquery'],
SCI_VERSION,
true
);
// 本地化脚本,传递数据到JavaScript
wp_localize_script('sci-chat-script', 'sci_chat', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('sci_chat_nonce'),
'settings' => get_option('sci_settings', []),
'strings' => [
'placeholder' => '请输入您的问题...',
'send' => '发送',
'connecting' => '连接中...',
'online' => '客服在线',
'offline' => '客服离线'
]
]);
}
/**
* 渲染聊天窗口
*/
public function render_chat_widget() {
$options = get_option('sci_settings');
$position = isset($options['chat_position']) ? $options['chat_position'] : 'bottom-right';
// 包含聊天窗口模板
include SCI_PLUGIN_PATH . 'templates/chat-widget.php';
}
}
第六步:创建前端JavaScript
在assets/js/frontend-script.js中,添加前端交互
/**
* 智能客服前端交互脚本
* 处理聊天窗口的用户交互
*/
(function($) {
'use strict';
// 聊天状态管理
const ChatManager = {
isOpen: false,
isMinimized: false,
messages: [],
isTyping: false,
init: function() {
this.bindEvents();
this.loadChatHistory();
this.updateConnectionStatus();
},
bindEvents: function() {
// 切换聊天窗口
$('#sci-toggle-chat').on('click', this.toggleChat.bind(this));
// 最小化/最大化
$('#sci-minimize-chat').on('click', this.toggleMinimize.bind(this));
// 发送消息
$('#sci-send-btn').on('click', this.sendMessage.bind(this));
// 回车发送消息
$('#sci-message-input').on('keypress', function(e) {
if (e.which === 13 && !e.shiftKey) {
e.preventDefault();
ChatManager.sendMessage();
}
});
// 关闭聊天
$('#sci-close-chat').on('click', this.closeChat.bind(this));
},
toggleChat: function() {
this.isOpen = !this.isOpen;
const $chatBox = $('#sci-chat-box');
const $toggleBtn = $('#sci-toggle-chat');
if (this.isOpen) {
$chatBox.addClass('open');
$toggleBtn.addClass('active');
$('#sci-message-input').focus();
this.scrollToBottom();
} else {
$chatBox.removeClass('open');
$toggleBtn.removeClass('active');
}
},
toggleMinimize: function() {
this.isMinimized = !this.isMinimized;
const $chatBody = $('#sci-chat-body');
const $minimizeBtn = $('#sci-minimize-chat i');
if (this.isMinimized) {
$chatBody.slideUp();
$minimizeBtn.removeClass('fa-window-minimize').addClass('fa-window-maximize');
} else {
$chatBody.slideDown();
$minimizeBtn.removeClass('fa-window-maximize').addClass('fa-window-minimize');
this.scrollToBottom();
}
},
sendMessage: function() {
const $input = $('#sci-message-input');
const message = $input.val().trim();
if (!message) return;
// 添加用户消息到界面
this.addMessage(message, 'user');
$input.val('');
// 显示机器人正在输入
this.showTypingIndicator();
// 发送到服务器
$.ajax({
url: sci_chat.ajax_url,
type: 'POST',
data: {
action: 'sci_send_message',
nonce: sci_chat.nonce,
message: message,
user_data: this.getUserData()
},
success: (response) => {
this.hideTypingIndicator();
if (response.success) {
// 添加机器人回复
const botMessage = response.data.response || '抱歉,我暂时无法回答这个问题。';
this.addMessage(botMessage, 'bot');
// 保存到历史记录
this.saveToHistory(message, botMessage);
} else {
this.addMessage('发送失败:' + response.data.error, 'system');
}
},
error: () => {
this.hideTypingIndicator();
this.addMessage('网络错误,请稍后重试。', 'system');
}
});
},
addMessage: function(content, type) {
const timestamp = new Date().toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
});
const message = {
id: Date.now(),
content: this.escapeHtml(content),
type: type,
timestamp: timestamp
};
this.messages.push(message);
this.renderMessage(message);
this.scrollToBottom();
},
renderMessage: function(message) {
const $messages = $('#sci-messages');
let messageClass = '';
let avatar = '';
switch(message.type) {
case 'user':
messageClass = 'user-message';
avatar = '<div class="sci-avatar user-avatar">您</div>';
break;
case 'bot':
messageClass = 'bot-message';
avatar = '<div class="sci-avatar bot-avatar"><i class="fas fa-robot"></i></div>';
break;
case 'system':
messageClass = 'system-message';
break;
}
const messageHtml = `
<div class="sci-message ${messageClass}" data-id="${message.id}">
${avatar}
<div class="sci-message-content">
<div class="sci-message-text">${message.content}</div>
<div class="sci-message-time">${message.timestamp}</div>
</div>
</div>
`;
$messages.append(messageHtml);
},
showTypingIndicator: function() {
this.isTyping = true;
const $typingIndicator = $(`
<div class="sci-typing-indicator">
<div class="sci-avatar bot-avatar"><i class="fas fa-robot"></i></div>
<div class="sci-message-content">
<div class="sci-typing-dots">
<span></span><span></span><span></span>
</div>
</div>
</div>
`);
$('#sci-messages').append($typingIndicator);
this.scrollToBottom();
},
hideTypingIndicator: function() {
this.isTyping = false;
$('.sci-typing-indicator').remove();
},
scrollToBottom: function() {
const $messages = $('#sci-messages');
$messages.scrollTop($messages[0].scrollHeight);
},
escapeHtml: function(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
},
getUserData: function() {
// 从Cookie或本地存储获取用户数据
return {
user_id: this.getUserId(),
page_url: window.location.href,
user_agent: navigator.userAgent
};
},
getUserId: function() {
let userId = localStorage.getItem('sci_user_id');
if (!userId) {
userId = 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
localStorage.setItem('sci_user_id', userId);
}
return userId;
},
loadChatHistory: function() {
// 从本地存储加载历史记录
const history = localStorage.getItem('sci_chat_history');
if (history) {
this.messages = JSON.parse(history);
this.messages.forEach(msg => this.renderMessage(msg));
}
},
saveToHistory: function(userMsg, botMsg) {
// 保存最近的50条消息
if (this.messages.length > 50) {
this.messages = this.messages.slice(-50);
}
localStorage.setItem('sci_chat_history', JSON.stringify(this.messages));
},
updateConnectionStatus: function() {
// 检查API连接状态
$.ajax({
url: sci_chat.ajax_url,
type: 'POST',
data: {
action: 'sci_check_status',
nonce: sci_chat.nonce
},
success: (response) => {
const $status = $('#sci-chat-status');
if (response.success) {
$status.text(sci_chat.strings.online).removeClass('offline').addClass('online');
} else {
$status.text(sci_chat.strings.offline).removeClass('online').addClass('offline');
}
}
});
},
closeChat: function() {
$('#sci-chat-box').remove();
$('#sci-toggle-chat').remove();
localStorage.removeItem('sci_chat_open');
}
};
// 页面加载完成后初始化
$(document).ready(function() {
ChatManager.init();
// 检查上次是否打开了聊天窗口
if (localStorage.getItem('sci_chat_open') === 'true') {
setTimeout(() => ChatManager.toggleChat(), 1000);
}
// 页面离开时保存状态
$(window).on('beforeunload', function() {
localStorage.setItem('sci_chat_open', ChatManager.isOpen);
});
});
})(jQuery);
第七步:创建CSS样式文件
在assets/css/chat-style.css中,添加前端样式:
/* 智能客服聊天窗口样式 */
/* 聊天触发按钮 */
#sci-toggle-chat {
position: fixed;
bottom: 20px;
right: 20px;
width: 60px;
height: 60px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 50%;
color: white;
border: none;
cursor: pointer;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
z-index: 9998;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
}
#sci-toggle-chat:hover {
transform: scale(1.1);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}
#sci-toggle-chat i {
font-size: 24px;
transition: transform 0.3s ease;
}
#sci-toggle-chat.active i {
transform: rotate(180deg);
}
/* 聊天主窗口 */
#sci-chat-box {
position: fixed;
bottom: 90px;
right: 20px;
width: 380px;
max-width: calc(100vw - 40px);
height: 500px;
background: white;
border-radius: 12px;
box-shadow: 0 5px 35px rgba(0, 0, 0, 0.15);
z-index: 9999;
display: none;
flex-direction: column;
overflow: hidden;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
#sci-chat-box.open {
display: flex;
animation: sciSlideIn 0.3s ease;
}
@keyframes sciSlideIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* 聊天头部 */
#sci-chat-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 15px 20px;
display: flex;
align-items: center;
justify-content: space-between;
}
#sci-chat-title {
display: flex;
align-items: center;
gap: 10px;
}
#sci-chat-title h3 {
margin: 0;
font-size: 16px;
font-weight: 600;
}
#sci-chat-status {
font-size: 12px;
padding: 2px 8px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.2);
}
#sci-chat-status.online {
background: rgba(46, 204, 113, 0.3);
}
#sci-chat-status.offline {
background: rgba(231, 76, 60, 0.3);
}
#sci-chat-actions {
display: flex;
gap: 10px;
}
#sci-chat-actions button {
background: none;
border: none;
color: white;
cursor: pointer;
opacity: 0.8;
transition: opacity 0.2s;
font-size: 14px;
}
#sci-chat-actions button:hover {
opacity: 1;
}
/* 聊天消息区域 */
#sci-chat-body {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
#sci-messages {
flex: 1;
padding: 20px;
overflow-y: auto;
background: #f8f9fa;
}
/* 消息样式 */
.sci-message {
display: flex;
margin-bottom: 16px;
animation: sciMessageAppear 0.3s ease;
}
@keyframes sciMessageAppear {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.sci-avatar {
width: 32px;
height: 32px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
margin-right: 10px;
font-size: 12px;
font-weight: bold;
}
.user-avatar {
background: #667eea;
color: white;
}
.bot-avatar {
background: #764ba2;
color: white;
}
.sci-message-content {
max-width: 70%;
}
.sci-message-text {
padding: 12px 16px;
border-radius: 18px;
line-height: 1.4;
word-wrap: break-word;
}
.user-message .sci-message-content {
margin-left: auto;
}
.user-message .sci-message-text {
background: #667eea;
color: white;
border-bottom-right-radius: 4px;
}
.bot-message .sci-message-text {
background: white;
color: #333;
border: 1px solid #e0e0e0;
border-bottom-left-radius: 4px;
}
.system-message {
justify-content: center;
}
.system-message .sci-message-text {
background: #f0f0f0;
color: #666;
font-size: 12px;
padding: 6px 12px;
border-radius: 12px;
}
.sci-message-time {
font-size: 11px;
color: #999;
margin-top: 4px;
padding: 0 4px;
}
.user-message .sci-message-time {
text-align: right;
}
/* 输入区域 */
#sci-chat-input {
padding: 15px;
background: white;
border-top: 1px solid #e0e0e0;
}
#sci-input-container {
display: flex;
gap: 10px;
}
#sci-message-input {
flex: 1;
padding: 12px 16px;
border: 1px solid #ddd;
border-radius: 24px;
font-size: 14px;
resize: none;
outline: none;
transition: border-color 0.2s;
}
#sci-message-input:focus {
border-color: #667eea;
}
#sci-send-btn {
width: 44px;
height: 44px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
border-radius: 50%;
color: white;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: transform 0.2s;
}
#sci-send-btn:hover {
transform: scale(1.05);
}
/* 正在输入指示器 */
.sci-typing-indicator {
display: flex;
align-items: center;
margin-bottom: 16px;
}
.sci-typing-dots {
display: flex;
gap: 4px;
padding: 12px 16px;
background: white;
border: 1px solid #e0e0e0;
border-radius: 18px;
border-bottom-left-radius: 4px;
}
.sci-typing-dots span {
width: 8px;
height: 8px;
background: #ccc;
border-radius: 50%;
animation: sciTyping 1.4s infinite ease-in-out;
}
.sci-typing-dots span:nth-child(1) { animation-delay: -0.32s; }
.sci-typing-dots span:nth-child(2) { animation-delay: -0.16s; }
@keyframes sciTyping {
0%, 80%, 100% { transform: scale(0); }
40% { transform: scale(1); }
}
/* 响应式设计 */
@media (max-width: 480px) {
#sci-chat-box {
width: calc(100vw - 40px);
height: 70vh;
bottom: 80px;
right: 20px;
left: 20px;
}
.sci-message-content {
max-width: 85%;
}
}
/* 位置变体 */
#sci-chat-box.bottom-left {
right: auto;
left: 20px;
}
#sci-chat-box.top-right {
bottom: auto;
top: 20px;
}
#sci-chat-box.top-left {
bottom: auto;
right: auto;
top: 20px;
left: 20px;
}
第八步:创建聊天窗口模板
在templates/chat-widget.php中,添加HTML结构:
<?php
/**
* 聊天窗口模板
* 注意:此文件仅包含HTML结构,不包含PHP逻辑
*/
$options = get_option('sci_settings');
