文章目录[隐藏]
WordPress集成教程:连接企业微信或钉钉实现消息互通,通过代码二次开发实现常用互联网小工具功能
引言:为什么需要将WordPress与企业通讯工具集成?
在当今数字化办公环境中,信息流通的效率和及时性直接影响企业运营效果。WordPress作为全球最流行的内容管理系统,承载着大量企业的官方网站、博客、产品展示甚至内部知识库。而企业微信和钉钉作为国内主流的企业通讯协作平台,已经成为日常工作中不可或缺的工具。
将WordPress与企业微信或钉钉集成,可以实现:
- 网站内容更新实时通知到工作群组
- 用户提交的表单数据即时推送到相关负责人
- 评论审核提醒、订单状态变更等业务通知
- 实现跨平台的信息同步与协作
本文将详细介绍如何通过WordPress代码二次开发,实现与企业微信或钉钉的消息互通,并扩展实现一些常用的互联网小工具功能。
第一部分:准备工作与环境配置
1.1 了解企业微信与钉钉开放平台
企业微信开放平台提供了丰富的API接口,包括:
- 消息推送接口:支持文本、图文、卡片等多种消息格式
- 部门与成员管理:获取组织架构信息
- 应用管理:创建自定义应用并获取访问凭证
钉钉开放平台同样提供了:
- 工作通知接口:向用户或部门发送消息
- 群机器人:通过Webhook方式发送消息到群聊
- 免登授权:实现用户身份验证
1.2 WordPress开发环境搭建
在进行二次开发前,需要准备:
- 本地开发环境:推荐使用Local by Flywheel或XAMPP
- 代码编辑器:VS Code或PHPStorm
-
WordPress调试配置:在wp-config.php中启用调试模式
define('WP_DEBUG', true); define('WP_DEBUG_LOG', true); define('WP_DEBUG_DISPLAY', false);
1.3 创建WordPress插件框架
我们将创建一个独立的插件来实现所有功能:
<?php
/**
* Plugin Name: 企业通讯集成工具
* Plugin URI: https://yourwebsite.com/
* Description: 连接企业微信或钉钉实现消息互通,集成常用小工具
* Version: 1.0.0
* Author: Your Name
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('ECIT_VERSION', '1.0.0');
define('ECIT_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('ECIT_PLUGIN_URL', plugin_dir_url(__FILE__));
// 初始化插件
require_once ECIT_PLUGIN_DIR . 'includes/class-core.php';
ECIT_Core::init();
第二部分:企业微信集成实现
2.1 企业微信应用配置与认证
首先需要在企业微信管理后台创建应用:
- 登录企业微信管理后台
- 进入"应用管理" → "自建应用" → "创建应用"
-
获取以下关键信息:
- CorpID:企业ID
- AgentId:应用ID
- Secret:应用密钥
2.2 获取访问令牌(Access Token)
企业微信API调用需要Access Token,以下是获取Token的类实现:
class ECIT_WeChat_Work {
private $corp_id;
private $agent_id;
private $secret;
private $access_token;
private $token_expire;
public function __construct($corp_id, $agent_id, $secret) {
$this->corp_id = $corp_id;
$this->agent_id = $agent_id;
$this->secret = $secret;
$this->get_access_token();
}
private function get_access_token() {
$transient_key = 'ecit_wechat_token_' . $this->agent_id;
$cached_token = get_transient($transient_key);
if ($cached_token !== false) {
$this->access_token = $cached_token;
return;
}
$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
$params = [
'corpid' => $this->corp_id,
'corpsecret' => $this->secret
];
$response = wp_remote_get(add_query_arg($params, $url));
if (is_wp_error($response)) {
error_log('企业微信获取Token失败: ' . $response->get_error_message());
return false;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['access_token'])) {
$this->access_token = $body['access_token'];
// Token有效期为7200秒,我们设置为7000秒过期
set_transient($transient_key, $this->access_token, 7000);
return true;
}
error_log('企业微信Token获取失败: ' . json_encode($body));
return false;
}
public function get_token() {
return $this->access_token;
}
}
2.3 实现消息发送功能
class ECIT_WeChat_Message {
private $wechat_work;
public function __construct($wechat_work) {
$this->wechat_work = $wechat_work;
}
/**
* 发送文本消息
*/
public function send_text($content, $to_user = '@all', $to_party = '', $to_tag = '') {
$token = $this->wechat_work->get_token();
if (!$token) {
return false;
}
$url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token}";
$data = [
'touser' => $to_user,
'toparty' => $to_party,
'totag' => $to_tag,
'msgtype' => 'text',
'agentid' => $this->wechat_work->agent_id,
'text' => [
'content' => $content
],
'safe' => 0,
'enable_id_trans' => 0,
'enable_duplicate_check' => 0
];
$response = wp_remote_post($url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
'timeout' => 10
]);
return $this->handle_response($response);
}
/**
* 发送图文消息
*/
public function send_news($articles, $to_user = '@all') {
$token = $this->wechat_work->get_token();
if (!$token) {
return false;
}
$url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token}";
$data = [
'touser' => $to_user,
'msgtype' => 'news',
'agentid' => $this->wechat_work->agent_id,
'news' => [
'articles' => $articles
]
];
$response = wp_remote_post($url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data, JSON_UNESCAPED_UNICODE)
]);
return $this->handle_response($response);
}
private function handle_response($response) {
if (is_wp_error($response)) {
error_log('企业微信消息发送失败: ' . $response->get_error_message());
return false;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($body['errcode'] == 0) {
return true;
} else {
error_log('企业微信消息发送失败: ' . json_encode($body));
return false;
}
}
}
2.4 WordPress钩子集成示例
将WordPress事件与企业微信通知绑定:
class ECIT_WordPress_Hooks {
private $wechat_message;
public function __construct($wechat_message) {
$this->wechat_message = $wechat_message;
$this->init_hooks();
}
private function init_hooks() {
// 新文章发布通知
add_action('publish_post', [$this, 'notify_new_post'], 10, 2);
// 新评论通知
add_action('comment_post', [$this, 'notify_new_comment'], 10, 3);
// 用户注册通知
add_action('user_register', [$this, 'notify_new_user']);
// WooCommerce新订单通知
add_action('woocommerce_new_order', [$this, 'notify_new_order'], 10, 2);
}
public function notify_new_post($post_id, $post) {
if ($post->post_status != 'publish' || $post->post_type != 'post') {
return;
}
$author = get_user_by('ID', $post->post_author);
$post_url = get_permalink($post_id);
$message = "📢 新文章发布通知nn";
$message .= "标题:{$post->post_title}n";
$message .= "作者:{$author->display_name}n";
$message .= "摘要:" . wp_trim_words(strip_tags($post->post_content), 50) . "n";
$message .= "链接:{$post_url}";
$this->wechat_message->send_text($message);
}
public function notify_new_comment($comment_id, $approved, $commentdata) {
if ($approved != 1) {
return;
}
$post = get_post($commentdata['comment_post_ID']);
$comment = get_comment($comment_id);
$message = "💬 新评论通知nn";
$message .= "文章:{$post->post_title}n";
$message .= "评论人:{$comment->comment_author}n";
$message .= "内容:" . wp_trim_words($comment->comment_content, 30) . "n";
$message .= "管理链接:" . admin_url("comment.php?action=editcomment&c={$comment_id}");
$this->wechat_message->send_text($message);
}
public function notify_new_user($user_id) {
$user = get_user_by('ID', $user_id);
$message = "👤 新用户注册nn";
$message .= "用户名:{$user->user_login}n";
$message .= "邮箱:{$user->user_email}n";
$message .= "注册时间:" . date('Y-m-d H:i:s') . "n";
$message .= "管理链接:" . admin_url("user-edit.php?user_id={$user_id}");
$this->wechat_message->send_text($message);
}
}
第三部分:钉钉集成实现
3.1 钉钉机器人配置
钉钉群机器人提供了更简单的集成方式:
class ECIT_DingTalk_Robot {
private $webhook_url;
private $secret;
public function __construct($webhook_url, $secret = '') {
$this->webhook_url = $webhook_url;
$this->secret = $secret;
}
/**
* 生成签名
*/
private function generate_sign($timestamp) {
if (empty($this->secret)) {
return '';
}
$string_to_sign = $timestamp . "n" . $this->secret;
$sign = base64_encode(hash_hmac('sha256', $string_to_sign, $this->secret, true));
return urlencode($sign);
}
/**
* 发送文本消息
*/
public function send_text($content, $at_mobiles = [], $at_all = false) {
$timestamp = time() * 1000;
$sign = $this->generate_sign($timestamp);
$url = $this->webhook_url;
if ($sign) {
$url .= "×tamp={$timestamp}&sign={$sign}";
}
$data = [
'msgtype' => 'text',
'text' => [
'content' => $content
],
'at' => [
'atMobiles' => $at_mobiles,
'isAtAll' => $at_all
]
];
$response = wp_remote_post($url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
'timeout' => 10
]);
return $this->handle_response($response);
}
/**
* 发送Markdown消息
*/
public function send_markdown($title, $text, $at_mobiles = [], $at_all = false) {
$timestamp = time() * 1000;
$sign = $this->generate_sign($timestamp);
$url = $this->webhook_url;
if ($sign) {
$url .= "×tamp={$timestamp}&sign={$sign}";
}
$data = [
'msgtype' => 'markdown',
'markdown' => [
'title' => $title,
'text' => $text
],
'at' => [
'atMobiles' => $at_mobiles,
'isAtAll' => $at_all
]
];
$response = wp_remote_post($url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data, JSON_UNESCAPED_UNICODE)
]);
return $this->handle_response($response);
}
/**
* 发送链接消息
*/
public function send_link($title, $text, $message_url, $pic_url = '') {
$timestamp = time() * 1000;
$sign = $this->generate_sign($timestamp);
$url = $this->webhook_url;
if ($sign) {
$url .= "×tamp={$timestamp}&sign={$sign}";
}
$data = [
'msgtype' => 'link',
'link' => [
'title' => $title,
'text' => $text,
'messageUrl' => $message_url,
'picUrl' => $pic_url
]
];
$response = wp_remote_post($url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data, JSON_UNESCAPED_UNICODE)
]);
return $this->handle_response($response);
}
private function handle_response($response) {
if (is_wp_error($response)) {
error_log('钉钉消息发送失败: ' . $response->get_error_message());
return false;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($body['errcode'] == 0) {
return true;
} else {
error_log('钉钉消息发送失败: ' . json_encode($body));
return false;
}
}
}
3.2 钉钉工作通知API集成
对于更复杂的企业应用,可以使用钉钉工作通知API:
class ECIT_DingTalk_Work_Notification {
private $app_key;
private $app_secret;
private $access_token;
public function __construct($app_key, $app_secret) {
$this->app_key = $app_key;
$this->app_secret = $app_secret;
$this->get_access_token();
}
private function get_access_token() {
$transient_key = 'ecit_dingtalk_token';
$cached_token = get_transient($transient_key);
if ($cached_token !== false) {
$this->access_token = $cached_token;
return;
}
$url = 'https://oapi.dingtalk.com/gettoken';
$params = [
'appkey' => $this->app_key,
'appsecret' => $this->app_secret
];
$response = wp_remote_get(add_query_arg($params, $url));
if (is_wp_error($response)) {
error_log('钉钉获取Token失败: ' . $response->get_error_message());
return false;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($body['errcode'] == 0) {
$this->access_token = $body['access_token'];
set_transient($transient_key, $this->access_token, 7000);
return true;
}
error_log('钉钉Token获取失败: ' . json_encode($body));
return false;
}
/**
* 发送工作通知
*/
public function send_notification($userid_list, $dept_id_list, $msg) {
$token = $this->access_token;
if (!$token) {
return false;
}
$url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={$token}";
$data = [
'agent_id' => 'your_agent_id', // 需要在钉钉后台获取
'userid_list' => implode(',', $userid_list),
'dept_id_list' => implode(',', $dept_id_list),
'to_all_user' => false,
'msg' => $msg
];
$response = wp_remote_post($url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data, JSON_UNESCAPED_UNICODE)
]);
return $this->handle_response($response);
}
}
第四部分:常用互联网小工具功能实现
4
4.1 短链接生成工具
短链接服务在内容分享和营销中非常实用,我们可以集成多种短链接API:
class ECIT_Short_URL_Tool {
/**
* 使用百度短链接API
*/
public static function baidu_shorten($long_url) {
$api_url = 'https://dwz.cn/admin/v2/create';
$token = get_option('ecit_baidu_dwz_token', '');
if (empty($token)) {
return new WP_Error('no_token', '未配置百度短链接Token');
}
$data = [
'url' => $long_url,
'termOfValidity' => '1-year' // 有效期:1年
];
$response = wp_remote_post($api_url, [
'headers' => [
'Content-Type' => 'application/json',
'Token' => $token
],
'body' => json_encode($data),
'timeout' => 10
]);
if (is_wp_error($response)) {
return $response;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['Code']) && $body['Code'] == 0) {
return $body['ShortUrl'];
}
return new WP_Error('api_error', $body['ErrMsg'] ?? '生成短链接失败');
}
/**
* 使用新浪短链接API
*/
public static function sina_shorten($long_url) {
$api_url = 'http://api.t.sina.com.cn/short_url/shorten.json';
$source = get_option('ecit_sina_app_key', '');
$params = [
'source' => $source,
'url_long' => $long_url
];
$response = wp_remote_get(add_query_arg($params, $api_url));
if (is_wp_error($response)) {
return $response;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body[0]['url_short'])) {
return $body[0]['url_short'];
}
return new WP_Error('api_error', '生成短链接失败');
}
/**
* 自建短链接服务
*/
public static function custom_shorten($long_url, $custom_slug = '') {
global $wpdb;
$table_name = $wpdb->prefix . 'ecit_short_urls';
// 检查表是否存在,不存在则创建
if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
long_url text NOT NULL,
short_slug varchar(100) NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
click_count int(11) DEFAULT 0,
PRIMARY KEY (id),
UNIQUE KEY short_slug (short_slug),
KEY long_url (long_url(100))
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
// 如果已存在该长链接,返回已有的短链接
$existing = $wpdb->get_row($wpdb->prepare(
"SELECT short_slug FROM $table_name WHERE long_url = %s",
$long_url
));
if ($existing) {
return home_url('/s/' . $existing->short_slug);
}
// 生成短码
if (empty($custom_slug)) {
$short_slug = self::generate_slug();
} else {
$short_slug = sanitize_title($custom_slug);
// 检查是否已存在
$exists = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $table_name WHERE short_slug = %s",
$short_slug
));
if ($exists) {
return new WP_Error('slug_exists', '该短码已存在');
}
}
// 插入数据库
$wpdb->insert($table_name, [
'long_url' => $long_url,
'short_slug' => $short_slug
]);
return home_url('/s/' . $short_slug);
}
/**
* 生成随机短码
*/
private static function generate_slug($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characters_length = strlen($characters);
$random_string = '';
for ($i = 0; $i < $length; $i++) {
$random_string .= $characters[rand(0, $characters_length - 1)];
}
return $random_string;
}
/**
* 短链接重定向处理
*/
public static function handle_redirect() {
if (preg_match('#^/s/([a-zA-Z0-9]+)$#', $_SERVER['REQUEST_URI'], $matches)) {
$slug = $matches[1];
global $wpdb;
$table_name = $wpdb->prefix . 'ecit_short_urls';
$result = $wpdb->get_row($wpdb->prepare(
"SELECT long_url FROM $table_name WHERE short_slug = %s",
$slug
));
if ($result) {
// 更新点击次数
$wpdb->query($wpdb->prepare(
"UPDATE $table_name SET click_count = click_count + 1 WHERE short_slug = %s",
$slug
));
// 重定向
wp_redirect($result->long_url, 301);
exit;
}
}
}
}
4.2 二维码生成工具
class ECIT_QR_Code_Tool {
/**
* 使用Google Charts API生成二维码
*/
public static function google_qrcode($content, $size = 200, $margin = 4) {
$params = [
'cht' => 'qr',
'chs' => $size . 'x' . $size,
'chl' => urlencode($content),
'choe' => 'UTF-8',
'chld' => 'L|' . $margin
];
$url = 'https://chart.googleapis.com/chart?' . http_build_query($params);
// 下载图片到本地
$upload_dir = wp_upload_dir();
$filename = 'qrcode-' . md5($content . $size) . '.png';
$filepath = $upload_dir['path'] . '/' . $filename;
if (!file_exists($filepath)) {
$response = wp_remote_get($url);
if (!is_wp_error($response)) {
file_put_contents($filepath, wp_remote_retrieve_body($response));
}
}
return $upload_dir['url'] . '/' . $filename;
}
/**
* 使用PHP QR Code库生成二维码
*/
public static function php_qrcode($content, $size = 10, $margin = 1) {
// 引入PHP QR Code库
if (!class_exists('QRcode')) {
require_once ECIT_PLUGIN_DIR . 'lib/phpqrcode/qrlib.php';
}
$upload_dir = wp_upload_dir();
$filename = 'qrcode-' . md5($content . $size) . '.png';
$filepath = $upload_dir['path'] . '/' . $filename;
if (!file_exists($filepath)) {
QRcode::png($content, $filepath, QR_ECLEVEL_L, $size, $margin);
}
return $upload_dir['url'] . '/' . $filename;
}
/**
* 生成带Logo的二维码
*/
public static function qrcode_with_logo($content, $logo_path, $size = 10) {
// 先生成普通二维码
$qrcode_path = self::php_qrcode($content, $size, 0);
$qrcode_path = str_replace(wp_upload_dir()['url'], wp_upload_dir()['path'], $qrcode_path);
// 加载二维码图片
$qrcode = imagecreatefrompng($qrcode_path);
$qrcode_width = imagesx($qrcode);
$qrcode_height = imagesy($qrcode);
// 加载Logo图片
$logo_info = getimagesize($logo_path);
$logo_type = $logo_info[2];
switch ($logo_type) {
case IMAGETYPE_JPEG:
$logo = imagecreatefromjpeg($logo_path);
break;
case IMAGETYPE_PNG:
$logo = imagecreatefrompng($logo_path);
break;
default:
return $qrcode_path;
}
$logo_width = imagesx($logo);
$logo_height = imagesy($logo);
// 计算Logo大小(二维码的1/5)
$new_logo_width = $qrcode_width / 5;
$new_logo_height = $logo_height * ($new_logo_width / $logo_width);
// 重新调整Logo大小
$resized_logo = imagecreatetruecolor($new_logo_width, $new_logo_height);
imagecopyresampled($resized_logo, $logo, 0, 0, 0, 0,
$new_logo_width, $new_logo_height, $logo_width, $logo_height);
// 合并图片
$dst_x = ($qrcode_width - $new_logo_width) / 2;
$dst_y = ($qrcode_height - $new_logo_height) / 2;
imagecopymerge($qrcode, $resized_logo, $dst_x, $dst_y, 0, 0,
$new_logo_width, $new_logo_height, 100);
// 保存新图片
$filename = 'qrcode-logo-' . md5($content) . '.png';
$filepath = wp_upload_dir()['path'] . '/' . $filename;
imagepng($qrcode, $filepath);
// 释放内存
imagedestroy($qrcode);
imagedestroy($logo);
imagedestroy($resized_logo);
return wp_upload_dir()['url'] . '/' . $filename;
}
/**
* 生成文章二维码短代码
*/
public static function qrcode_shortcode($atts) {
$atts = shortcode_atts([
'size' => 200,
'logo' => '',
'post_id' => get_the_ID()
], $atts);
$post_url = get_permalink($atts['post_id']);
$post_title = get_the_title($atts['post_id']);
if (!empty($atts['logo'])) {
$logo_path = get_attached_file($atts['logo']);
$qrcode_url = self::qrcode_with_logo($post_url, $logo_path);
} else {
$qrcode_url = self::google_qrcode($post_url, $atts['size']);
}
return sprintf(
'<div class="post-qrcode">
<img src="%s" alt="%s" width="%d" height="%d">
<p>扫描二维码阅读文章</p>
</div>',
esc_url($qrcode_url),
esc_attr($post_title),
$atts['size'],
$atts['size']
);
}
}
4.3 数据统计与分析工具
class ECIT_Analytics_Tool {
/**
* 获取网站访问统计
*/
public static function get_visitor_stats($days = 30) {
global $wpdb;
$results = $wpdb->get_results($wpdb->prepare(
"SELECT DATE(visit_time) as date,
COUNT(*) as visits,
COUNT(DISTINCT ip_address) as unique_visitors
FROM {$wpdb->prefix}ecit_visits
WHERE visit_time >= DATE_SUB(NOW(), INTERVAL %d DAY)
GROUP BY DATE(visit_time)
ORDER BY date DESC",
$days
));
return $results;
}
/**
* 记录访问数据
*/
public static function track_visit() {
if (is_admin() || wp_doing_ajax() || wp_doing_cron()) {
return;
}
global $wpdb;
$table_name = $wpdb->prefix . 'ecit_visits';
// 检查表是否存在
if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
ip_address varchar(45) NOT NULL,
user_agent text,
page_url varchar(500) NOT NULL,
referrer varchar(500),
visit_time datetime DEFAULT CURRENT_TIMESTAMP,
user_id bigint(20) DEFAULT 0,
PRIMARY KEY (id),
KEY ip_address (ip_address),
KEY visit_time (visit_time),
KEY user_id (user_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
$data = [
'ip_address' => self::get_client_ip(),
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
'page_url' => (isset($_SERVER['HTTPS']) ? 'https' : 'http') .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]",
'referrer' => $_SERVER['HTTP_REFERER'] ?? '',
'user_id' => get_current_user_id()
];
$wpdb->insert($table_name, $data);
}
/**
* 获取客户端IP
*/
private static function get_client_ip() {
$ip_keys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];
foreach ($ip_keys as $key) {
if (array_key_exists($key, $_SERVER)) {
foreach (explode(',', $_SERVER[$key]) as $ip) {
$ip = trim($ip);
if (filter_var($ip, FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
}
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
/**
* 获取热门文章
*/
public static function get_popular_posts($limit = 10, $days = 30) {
global $wpdb;
$results = $wpdb->get_results($wpdb->prepare(
"SELECT p.ID, p.post_title,
COUNT(v.id) as view_count,
MAX(v.visit_time) as last_visit
FROM {$wpdb->prefix}ecit_visits v
INNER JOIN {$wpdb->posts} p ON v.page_url LIKE CONCAT('%%', p.guid, '%%')
WHERE v.visit_time >= DATE_SUB(NOW(), INTERVAL %d DAY)
AND p.post_status = 'publish'
AND p.post_type = 'post'
GROUP BY p.ID
ORDER BY view_count DESC
LIMIT %d",
$days, $limit
));
return $results;
}
/**
* 生成统计报告
*/
public static function generate_report($period = 'daily') {
$stats = self::get_visitor_stats($period == 'daily' ? 1 : 30);
$popular_posts = self::get_popular_posts(5, $period == 'daily' ? 1 : 30);
$report = "📊 网站访问统计报告nn";
if ($period == 'daily') {
$report .= "📅 日期: " . date('Y-m-d') . "n";
} else {
$report .= "📅 周期: 最近30天n";
}
$total_visits = 0;
$total_visitors = 0;
foreach ($stats as $stat) {
$total_visits += $stat->visits;
$total_visitors += $stat->unique_visitors;
}
$report .= "👥 总访问量: " . $total_visits . "n";
$report .= "👤 独立访客: " . $total_visitors . "nn";
$report .= "🔥 热门文章:n";
foreach ($popular_posts as $index => $post) {
$report .= ($index + 1) . ". " . $post->post_title .
" (" . $post->view_count . "次)n";
}
return $report;
}
}
4.4 内容自动发布工具
class ECIT_Auto_Publish_Tool {
/**
* 从RSS源自动发布文章
*/
