文章目录[隐藏]
手把手教程:为WordPress集成SEO分析与优化工具,通过代码二次开发实现常用互联网小工具功能
引言:为什么WordPress需要SEO工具集成?
在当今数字时代,拥有一个网站只是第一步,让网站在搜索引擎中获得良好排名才是成功的关键。WordPress作为全球最受欢迎的内容管理系统,虽然拥有众多SEO插件,但很多时候这些通用解决方案无法完全满足特定需求。通过代码二次开发,我们可以为WordPress网站集成更精准、更高效的SEO分析与优化工具,同时实现各种实用的互联网小工具功能。
本教程将引导您从零开始,通过PHP代码开发,为WordPress网站添加自定义SEO分析功能,并集成多种实用工具。无论您是WordPress开发者、网站管理员还是SEO专家,都能从中获得实用的技术指导。
第一章:准备工作与环境搭建
1.1 开发环境要求
在开始之前,请确保您具备以下环境:
- WordPress 5.0或更高版本
- PHP 7.4或更高版本(建议使用PHP 8.0+)
- MySQL 5.6或更高版本
- 代码编辑器(如VS Code、Sublime Text或PHPStorm)
- FTP客户端或服务器直接访问权限
- 基本的PHP、HTML、CSS和JavaScript知识
1.2 创建自定义插件框架
为了避免主题更新导致代码丢失,我们将创建一个独立的WordPress插件:
<?php
/**
* Plugin Name: SEO分析与工具集成套件
* Plugin URI: https://yourwebsite.com/
* Description: 自定义SEO分析工具与互联网小工具集成
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('SEOTOOLS_VERSION', '1.0.0');
define('SEOTOOLS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SEOTOOLS_PLUGIN_URL', plugin_dir_url(__FILE__));
// 初始化插件
function seotools_init() {
// 插件初始化代码将在这里添加
}
add_action('plugins_loaded', 'seotools_init');
1.3 安全注意事项
在开始开发前,请牢记以下安全准则:
- 所有用户输入必须经过验证和清理
- 使用WordPress非ce和权限检查功能
- 对数据库查询使用预处理语句
- 限制API密钥和敏感信息的访问
第二章:核心SEO分析功能开发
2.1 页面SEO评分系统
我们将创建一个页面SEO评分系统,自动分析文章和页面的SEO表现:
// 在插件主文件中添加以下类
class SEOTools_Analyzer {
private $post_id;
private $score;
private $issues;
public function __construct($post_id) {
$this->post_id = $post_id;
$this->score = 0;
$this->issues = array();
}
// 分析文章标题
public function analyze_title() {
$title = get_the_title($this->post_id);
$title_length = mb_strlen($title);
if ($title_length == 0) {
$this->add_issue('标题为空', 'high');
return 0;
} elseif ($title_length < 30) {
$this->add_issue('标题过短(建议30-60字符)', 'medium');
return 5;
} elseif ($title_length > 60) {
$this->add_issue('标题过长(建议30-60字符)', 'medium');
return 5;
} else {
$this->add_issue('标题长度合适', 'positive');
return 10;
}
}
// 分析元描述
public function analyze_meta_description() {
$meta_description = get_post_meta($this->post_id, '_yoast_wpseo_metadesc', true);
if (empty($meta_description)) {
$this->add_issue('元描述为空', 'high');
return 0;
}
$desc_length = mb_strlen($meta_description);
if ($desc_length < 120) {
$this->add_issue('元描述过短(建议120-160字符)', 'medium');
return 5;
} elseif ($desc_length > 160) {
$this->add_issue('元描述过长(建议120-160字符)', 'medium');
return 5;
} else {
$this->add_issue('元描述长度合适', 'positive');
return 10;
}
}
// 分析内容可读性
public function analyze_readability() {
$content = get_post_field('post_content', $this->post_id);
$content = strip_tags($content);
// 计算段落数
$paragraphs = preg_split('/ns*n/', $content);
$paragraph_count = count($paragraphs);
// 计算句子数
$sentences = preg_split('/[.!?]+/', $content);
$sentence_count = count($sentences);
// 计算平均段落长度
if ($paragraph_count > 0 && $sentence_count > 0) {
$avg_sentences_per_para = $sentence_count / $paragraph_count;
if ($avg_sentences_per_para > 5) {
$this->add_issue('段落过长,建议拆分', 'medium');
return 5;
} elseif ($avg_sentences_per_para < 2) {
$this->add_issue('段落过短,建议合并', 'low');
return 7;
} else {
$this->add_issue('段落长度合适', 'positive');
return 10;
}
}
return 5;
}
// 分析图片ALT属性
public function analyze_images() {
$content = get_post_field('post_content', $this->post_id);
$images_without_alt = 0;
$total_images = 0;
if (preg_match_all('/<img[^>]+>/i', $content, $matches)) {
foreach ($matches[0] as $img_tag) {
$total_images++;
if (!preg_match('/alt=["'][^"']*["']/i', $img_tag)) {
$images_without_alt++;
}
}
}
if ($total_images == 0) {
$this->add_issue('内容中缺少图片', 'medium');
return 5;
} elseif ($images_without_alt > 0) {
$percentage = ($images_without_alt / $total_images) * 100;
$this->add_issue(sprintf('%d%%的图片缺少ALT属性', $percentage), 'medium');
return max(0, 10 - ($images_without_alt * 2));
} else {
$this->add_issue('所有图片都有ALT属性', 'positive');
return 10;
}
}
// 添加问题到列表
private function add_issue($message, $severity) {
$this->issues[] = array(
'message' => $message,
'severity' => $severity
);
}
// 执行完整分析
public function run_analysis() {
$scores = array(
'title' => $this->analyze_title(),
'meta_description' => $this->analyze_meta_description(),
'readability' => $this->analyze_readability(),
'images' => $this->analyze_images()
);
$this->score = array_sum($scores) / count($scores);
return array(
'score' => round($this->score, 1),
'issues' => $this->issues,
'details' => $scores
);
}
}
// 在文章编辑页面添加SEO分析框
function seotools_add_meta_box() {
add_meta_box(
'seotools_analysis',
'SEO分析报告',
'seotools_meta_box_callback',
array('post', 'page'),
'side',
'high'
);
}
add_action('add_meta_boxes', 'seotools_add_meta_box');
function seotools_meta_box_callback($post) {
$analyzer = new SEOTools_Analyzer($post->ID);
$analysis = $analyzer->run_analysis();
echo '<div class="seotools-analysis">';
echo '<div class="seotools-score-circle" style="width: 80px; height: 80px; border-radius: 50%; background: conic-gradient(#4CAF50 ' . ($analysis['score'] * 3.6) . 'deg, #f0f0f0 0deg); display: flex; align-items: center; justify-content: center; margin: 0 auto 15px;">';
echo '<div style="background: white; width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 18px;">' . $analysis['score'] . '/10</div>';
echo '</div>';
echo '<h3>发现的问题:</h3>';
echo '<ul style="margin-top: 10px;">';
foreach ($analysis['issues'] as $issue) {
$color = '#888';
if ($issue['severity'] == 'high') $color = '#f44336';
if ($issue['severity'] == 'medium') $color = '#ff9800';
if ($issue['severity'] == 'low') $color = '#ffc107';
if ($issue['severity'] == 'positive') $color = '#4CAF50';
echo '<li style="margin-bottom: 8px; padding-left: 5px; border-left: 3px solid ' . $color . ';">';
echo $issue['message'];
echo '</li>';
}
echo '</ul>';
echo '</div>';
// 添加内联样式
echo '<style>
.seotools-analysis h3 {
margin-top: 0;
border-bottom: 1px solid #ddd;
padding-bottom: 8px;
}
.seotools-analysis ul {
margin-left: 0;
padding-left: 0;
list-style: none;
}
</style>';
}
2.2 关键词密度分析器
关键词密度是SEO的重要指标之一。下面我们创建一个关键词密度分析工具:
class Keyword_Density_Analyzer {
public static function analyze($content, $keywords = array()) {
$results = array();
// 清理内容,移除HTML标签和短代码
$clean_content = strip_tags($content);
$clean_content = strip_shortcodes($clean_content);
// 转换为小写
$clean_content = mb_strtolower($clean_content);
// 获取所有词语
$words = preg_split('/s+/', $clean_content);
$total_words = count($words);
// 如果没有提供关键词,自动提取常见词
if (empty($keywords)) {
$keywords = self::extract_potential_keywords($clean_content);
}
// 分析每个关键词
foreach ($keywords as $keyword) {
$keyword_lower = mb_strtolower($keyword);
$keyword_count = 0;
// 计算关键词出现次数
foreach ($words as $word) {
if ($word == $keyword_lower) {
$keyword_count++;
}
}
// 计算密度
$density = ($total_words > 0) ? ($keyword_count / $total_words) * 100 : 0;
$results[$keyword] = array(
'count' => $keyword_count,
'density' => round($density, 2),
'recommendation' => self::get_density_recommendation($density)
);
}
return array(
'results' => $results,
'total_words' => $total_words
);
}
private static function extract_potential_keywords($content) {
$words = preg_split('/s+/', $content);
$word_freq = array();
// 统计词频
foreach ($words as $word) {
// 过滤短词和常见停用词
if (mb_strlen($word) > 3 && !in_array($word, self::get_stop_words())) {
if (!isset($word_freq[$word])) {
$word_freq[$word] = 0;
}
$word_freq[$word]++;
}
}
// 按频率排序
arsort($word_freq);
// 返回前10个最常出现的词
return array_slice(array_keys($word_freq), 0, 10);
}
private static function get_stop_words() {
return array('the', 'and', 'for', 'are', 'but', 'not', 'you', 'all', 'any', 'can', 'had', 'her', 'was', 'one', 'our', 'out', 'day', 'get', 'has', 'him', 'his', 'how', 'man', 'new', 'now', 'old', 'see', 'two', 'who', 'boy', 'did', 'its', 'let', 'put', 'say', 'she', 'too', 'use');
}
private static function get_density_recommendation($density) {
if ($density < 0.5) {
return '密度过低,建议增加关键词出现次数';
} elseif ($density > 2.5) {
return '密度过高,可能被搜索引擎视为关键词堆砌';
} else {
return '密度适中,保持当前水平';
}
}
}
// 在文章编辑页面添加关键词分析功能
function seotools_add_keyword_analysis() {
global $post;
if (!$post) return;
$content = $post->post_content;
$analysis = Keyword_Density_Analyzer::analyze($content);
echo '<div class="keyword-analysis">';
echo '<h3>关键词密度分析</h3>';
echo '<p>总词数: ' . $analysis['total_words'] . '</p>';
if (!empty($analysis['results'])) {
echo '<table class="widefat fixed" cellspacing="0">';
echo '<thead><tr><th>关键词</th><th>出现次数</th><th>密度</th><th>建议</th></tr></thead>';
echo '<tbody>';
foreach ($analysis['results'] as $keyword => $data) {
echo '<tr>';
echo '<td>' . htmlspecialchars($keyword) . '</td>';
echo '<td>' . $data['count'] . '</td>';
echo '<td>' . $data['density'] . '%</td>';
echo '<td>' . $data['recommendation'] . '</td>';
echo '</tr>';
}
echo '</tbody></table>';
} else {
echo '<p>未检测到显著关键词</p>';
}
echo '</div>';
}
add_action('edit_form_after_editor', 'seotools_add_keyword_analysis');
第三章:集成外部SEO工具API
3.1 集成Google PageSpeed Insights
Google PageSpeed Insights是评估网站性能的重要工具。下面我们将其集成到WordPress后台:
class PageSpeed_Integration {
private $api_key;
public function __construct($api_key = '') {
$this->api_key = $api_key;
}
public function analyze_url($url, $strategy = 'desktop') {
$api_url = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed';
$params = array(
'url' => $url,
'strategy' => $strategy,
'locale' => 'zh_CN'
);
if (!empty($this->api_key)) {
$params['key'] = $this->api_key;
}
$api_url .= '?' . http_build_query($params);
$response = wp_remote_get($api_url, array(
'timeout' => 30,
'sslverify' => false
));
if (is_wp_error($response)) {
return array(
'success' => false,
'error' => $response->get_error_message()
);
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['error'])) {
return array(
'success' => false,
'error' => $data['error']['message']
);
}
return array(
'success' => true,
'data' => $this->parse_results($data)
);
}
private function parse_results($data) {
$result = array();
// 提取性能分数
if (isset($data['lighthouseResult']['categories']['performance']['score'])) {
$result['performance_score'] = $data['lighthouseResult']['categories']['performance']['score'] * 100;
}
// 提取关键指标
$audits = $data['lighthouseResult']['audits'];
$important_metrics = array(
'first-contentful-paint' => '首次内容绘制(FCP)',
'largest-contentful-paint' => '最大内容绘制(LCP)',
'cumulative-layout-shift' => '累积布局偏移(CLS)',
'total-blocking-time' => '总阻塞时间(TBT)',
'speed-index' => '速度指数'
);
foreach ($important_metrics as $key => $label) {
if (isset($audits[$key])) {
$result['metrics'][$label] = array(
'score' => isset($audits[$key]['score']) ? $audits[$key]['score'] : null,
displayValue']) ? $audits[$key]['displayValue'] : 'N/A',
'description' => isset($audits[$key]['description']) ? $audits[$key]['description'] : ''
);
}
}
// 提取优化建议
$result['opportunities'] = array();
$opportunity_audits = array(
'render-blocking-resources',
'unused-css-rules',
'unused-javascript',
'modern-image-formats',
'offscreen-images'
);
foreach ($opportunity_audits as $audit_key) {
if (isset($audits[$audit_key]) && isset($audits[$audit_key]['details']['items'])) {
$result['opportunities'][$audits[$audit_key]['title']] = array(
'impact' => $audits[$audit_key]['score'] ? (1 - $audits[$audit_key]['score']) * 100 : 0,
'items' => count($audits[$audit_key]['details']['items'])
);
}
}
return $result;
}
// 创建后台页面
public function create_admin_page() {
add_submenu_page(
'tools.php',
'PageSpeed分析',
'PageSpeed分析',
'manage_options',
'pagespeed-analysis',
array($this, 'render_admin_page')
);
}
public function render_admin_page() {
$results = array();
if (isset($_POST['analyze_url'])) {
$url = esc_url_raw($_POST['url']);
$strategy = sanitize_text_field($_POST['strategy']);
if (!empty($url)) {
$results = $this->analyze_url($url, $strategy);
}
}
?>
<div class="wrap">
<h1>Google PageSpeed Insights分析</h1>
<form method="post" action="">
<table class="form-table">
<tr>
<th scope="row"><label for="url">网站URL</label></th>
<td>
<input type="url" id="url" name="url"
value="<?php echo isset($_POST['url']) ? esc_attr($_POST['url']) : get_site_url(); ?>"
class="regular-text" required>
</td>
</tr>
<tr>
<th scope="row"><label for="strategy">分析策略</label></th>
<td>
<select id="strategy" name="strategy">
<option value="desktop" <?php selected(isset($_POST['strategy']) ? $_POST['strategy'] : 'desktop', 'desktop'); ?>>桌面设备</option>
<option value="mobile" <?php selected(isset($_POST['strategy']) ? $_POST['strategy'] : 'desktop', 'mobile'); ?>>移动设备</option>
</select>
</td>
</tr>
</table>
<?php submit_button('开始分析', 'primary', 'analyze_url'); ?>
</form>
<?php if (!empty($results)): ?>
<?php if ($results['success']): ?>
<div class="pagespeed-results">
<h2>分析结果</h2>
<!-- 性能分数 -->
<div class="performance-score">
<h3>性能分数: <?php echo round($results['data']['performance_score']); ?>/100</h3>
<div class="score-bar">
<div class="score-fill" style="width: <?php echo $results['data']['performance_score']; ?>%;
background-color: <?php echo $this->get_score_color($results['data']['performance_score']); ?>;">
</div>
</div>
</div>
<!-- 核心指标 -->
<h3>核心Web指标</h3>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>指标</th>
<th>分数</th>
<th>数值</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<?php foreach ($results['data']['metrics'] as $label => $metric): ?>
<tr>
<td><?php echo esc_html($label); ?></td>
<td>
<?php if ($metric['score'] !== null): ?>
<span class="metric-score" style="color: <?php echo $this->get_score_color($metric['score'] * 100); ?>;">
<?php echo round($metric['score'] * 100); ?>/100
</span>
<?php else: ?>
N/A
<?php endif; ?>
</td>
<td><?php echo esc_html($metric['displayValue']); ?></td>
<td><?php echo wp_kses_post($metric['description']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- 优化建议 -->
<?php if (!empty($results['data']['opportunities'])): ?>
<h3>优化建议</h3>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>优化项</th>
<th>影响程度</th>
<th>问题数量</th>
</tr>
</thead>
<tbody>
<?php foreach ($results['data']['opportunities'] as $title => $opportunity): ?>
<tr>
<td><?php echo esc_html($title); ?></td>
<td>
<div class="impact-bar">
<div class="impact-fill" style="width: <?php echo $opportunity['impact']; ?>%;"></div>
<span><?php echo round($opportunity['impact']); ?>%</span>
</div>
</td>
<td><?php echo $opportunity['items']; ?>个</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<style>
.score-bar, .impact-bar {
height: 20px;
background: #f0f0f0;
border-radius: 10px;
overflow: hidden;
position: relative;
}
.score-fill, .impact-fill {
height: 100%;
transition: width 0.5s ease;
}
.impact-bar span {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 12px;
font-weight: bold;
}
.metric-score {
font-weight: bold;
}
</style>
<?php else: ?>
<div class="notice notice-error">
<p>分析失败: <?php echo esc_html($results['error']); ?></p>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
<?php
}
private function get_score_color($score) {
if ($score >= 90) return '#4CAF50';
if ($score >= 50) return '#FFC107';
return '#F44336';
}
}
// 初始化PageSpeed集成
$pagespeed_integration = new PageSpeed_Integration();
add_action('admin_menu', array($pagespeed_integration, 'create_admin_page'));
### 3.2 集成百度SEO数据查询
针对中文网站,集成百度SEO数据查询功能:
class Baidu_SEO_Integration {
public function create_admin_page() {
add_submenu_page(
'tools.php',
'百度SEO查询',
'百度SEO查询',
'manage_options',
'baidu-seo-check',
array($this, 'render_admin_page')
);
}
public function render_admin_page() {
$results = array();
if (isset($_POST['check_url'])) {
$url = esc_url_raw($_POST['url']);
if (!empty($url)) {
$results = $this->check_baidu_seo($url);
}
}
?>
<div class="wrap">
<h1>百度SEO数据查询</h1>
<form method="post" action="">
<table class="form-table">
<tr>
<th scope="row"><label for="url">查询URL</label></th>
<td>
<input type="url" id="url" name="url"
value="<?php echo isset($_POST['url']) ? esc_attr($_POST['url']) : get_site_url(); ?>"
class="regular-text" required>
<p class="description">请输入完整的URL地址</p>
</td>
</tr>
</table>
<?php submit_button('查询SEO数据', 'primary', 'check_url'); ?>
</form>
<?php if (!empty($results)): ?>
<div class="baidu-results">
<h2>查询结果</h2>
<div class="seo-metrics-grid">
<div class="metric-card">
<h3>百度收录</h3>
<div class="metric-value"><?php echo $results['indexed'] ? '已收录' : '未收录'; ?></div>
<?php if ($results['indexed']): ?>
<p class="metric-desc">该页面已被百度收录</p>
<?php else: ?>
<p class="metric-desc">该页面可能未被百度收录</p>
<?php endif; ?>
</div>
<div class="metric-card">
<h3>百度权重</h3>
<div class="metric-value"><?php echo esc_html($results['weight']); ?></div>
<p class="metric-desc">预估百度权重值</p>
</div>
<div class="metric-card">
<h3>反链数量</h3>
<div class="metric-value"><?php echo esc_html($results['backlinks']); ?></div>
<p class="metric-desc">外部链接数量</p>
</div>
<div class="metric-card">
<h3>关键词排名</h3>
<div class="metric-value"><?php echo esc_html($results['keywords_count']); ?>个</div>
<p class="metric-desc">有排名的关键词数量</p>
</div>
</div>
<?php if (!empty($results['keywords'])): ?>
<h3>关键词排名详情</h3>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>关键词</th>
<th>排名</th>
<th>搜索量</th>
<th>难度</th>
</tr>
</thead>
<tbody>
<?php foreach ($results['keywords'] as $keyword): ?>
<tr>
<td><?php echo esc_html($keyword['keyword']); ?></td>
<td>
<span class="rank-badge rank-<?php echo $this->get_rank_class($keyword['rank']); ?>">
第<?php echo $keyword['rank']; ?>名
</span>
</td>
<td><?php echo $this->format_search_volume($keyword['volume']); ?></td>
<td>
<div class="difficulty-bar">
<div class="difficulty-fill" style="width: <?php echo $keyword['difficulty']; ?>%;"></div>
<span><?php echo $keyword['difficulty']; ?>%</span>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<style>
.seo-metrics-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
margin: 20px 0;
}
.metric-card {
background: white;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
text-align: center;
}
.metric-card h3 {
margin-top: 0;
color: #333;
}
.metric-value {
font-size: 32px;
font-weight: bold;
color: #2271b1;
margin: 10px 0;
}
.metric-desc {
color: #666;
font-size: 14px;
margin: 0;
}
.rank-badge {
display: inline-block;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
font-weight: bold;
}
.rank-1 { background: #4CAF50; color: white; }
.rank-2 { background: #8BC34A; color: white; }
.rank-3 { background: #FFC107; color: black; }
.rank-4 { background: #FF9800; color: white; }
.rank-5 { background: #F44336; color: white; }
.difficulty-bar {
height: 20px;
background: #f0f0f0;
border-radius: 10px;
overflow: hidden;
position: relative;
}
.difficulty-fill {
height: 100%;
background: linear-gradient(90deg, #4CAF50, #FFC107, #F44336);
}
.difficulty-bar span {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 12px;
font-weight: bold;
}
</style>
<?php endif; ?>
</div>
<?php
}
private function check_baidu_seo($url) {
// 注意:这里使用模拟数据,实际应用中需要调用百度API
// 由于百度官方API限制,这里展示如何构建查询逻辑
$parsed_url = parse_url($url);
$domain = $parsed_url['host'];
// 模拟数据 - 实际应用中应调用相应API
return array(
'indexed' => true,
'weight' => '2',
'backlinks' => '1,234',
'keywords_count' => '45',
'keywords' => array(
array('keyword' => 'WordPress教程', 'rank' => 3, 'volume' => 2400, 'difficulty' => 65),
array('keyword' => 'SEO优化', 'rank' => 8, 'volume' => 4800, 'difficulty' => 78),
array('keyword' => '网站建设', 'rank' => 12, 'volume' => 3200, 'difficulty' => 72),
array('keyword' => '内容管理系统', 'rank' => 5, 'volume' => 1200, 'difficulty' => 58)
)
);
}
private function get_rank_class($rank) {
if ($rank <= 3) return '1';
if ($rank <= 10) return '2';
if ($rank <= 20) return '3';
if ($rank <= 50) return '4';
return '5';
}
private function format_search_volume($volume) {
if ($volume >= 1000) {
return round($volume / 1000, 1) . 'K';
}
return $volume;
}
}
// 初始化百度SEO集成
$baidu_seo_integration = new Baidu_SEO_Integration();
add_action('admin_menu', array($baidu_seo_integration, 'create_admin_page'));
## 第四章:实用互联网小工具集成
### 4.1 网站Uptime监控工具
创建一个简单的网站正常运行时间监控工具:
class Uptime_Monitor {
private $check_interval = 300; // 5分钟检查一次
public function __construct() {
// 添加定时任务
add_action('init', array($this, 'schedule_checks'));
add_action('uptime_check_event', array($this, 'perform_uptime_check'));
// 添加后台页面
add_action('admin_menu', array($this, 'add_admin_page'));
}
public function schedule_checks() {
if (!wp_next_scheduled('uptime_check_event')) {
wp_schedule_event(time(), 'five_minutes', 'uptime_check_event');
}
}
// 自定义定时任务间隔
public function add_cron_interval($schedules) {
$schedules['five_minutes'] = array(
'interval' => 300,
'display' => __('每5分钟')
);
return $schedules;
}
public function perform_uptime_check() {
$url = get_site_url();
$start_time = microtime(true);
$response = wp_remote_get($url, array(
'timeout' => 30,
'sslverify' => false
));
$end_time = microtime(true);
$response_time = round(($end_time - $start_time) * 1000); // 转换为毫秒
$status = array(
'timestamp' => current_time('timestamp'),
'response_code' => wp_remote_retrieve_response_code($response),
'response_time' => $response_time,
'success' => !is_wp_error($response) && wp_remote_retrieve_response_code($response) == 200
);
$this->save_check_result($status);
// 如果检测到宕机,发送通知
if (!$status['success']) {
$this->send_downtime_notification($status);
}
}
private function save_check_result($status) {
$history = get_option('uptime_monitor_history', array());
// 只保留最近24小时的数据(288条,每5分钟一条)
$history[] = $status;
if (count($history) > 288) {
$history = array_slice($history, -
