文章目录[隐藏]
一步步教你,为WordPress集成多源比价与优惠券聚合展示功能
引言:为什么WordPress需要比价与优惠券功能?
在当今电子商务蓬勃发展的时代,价格比较和优惠券获取已成为消费者购物决策的重要环节。对于内容创作者、博主和电商网站运营者而言,在WordPress网站上集成多源比价与优惠券聚合展示功能,不仅能显著提升用户体验,还能通过联盟营销等方式创造额外收入。
传统的WordPress网站通常只展示单一商品信息或有限的优惠内容,而通过代码二次开发实现多源比价与优惠券聚合功能,可以让您的网站成为用户购物的第一站。本文将详细指导您如何通过WordPress程序代码二次开发,实现这一实用功能,无需依赖昂贵的第三方插件,完全自主控制数据展示和更新逻辑。
第一部分:准备工作与环境搭建
1.1 开发环境要求
在开始开发之前,请确保您的环境满足以下要求:
- WordPress 5.0及以上版本
- PHP 7.4及以上版本(推荐PHP 8.0+)
- MySQL 5.6及以上或MariaDB 10.1及以上
- 至少512MB内存(推荐1GB以上)
- 支持cURL扩展的PHP环境
- 一个代码编辑器(如VS Code、Sublime Text或PHPStorm)
1.2 创建子主题保护核心文件
为了避免主题更新导致自定义代码丢失,我们首先创建一个子主题:
- 在WordPress的
wp-content/themes/目录下创建新文件夹,命名为my-custom-theme - 在该文件夹中创建
style.css文件,添加以下内容:
/*
Theme Name: My Custom Theme
Template: your-parent-theme-folder-name
Version: 1.0.0
Description: 子主题用于添加比价和优惠券功能
*/
- 创建
functions.php文件,初始内容可以为空 - 在WordPress后台启用这个子主题
1.3 安全备份策略
在进行任何代码修改前,请确保:
- 完整备份网站文件和数据库
- 使用版本控制系统(如Git)跟踪代码变更
- 在本地或 staging 环境测试后再部署到生产环境
第二部分:设计数据库结构
2.1 创建自定义数据表
我们需要创建几个自定义数据表来存储比价和优惠券信息。在子主题的functions.php中添加以下代码:
// 创建自定义数据表
function create_price_comparison_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
// 商品信息表
$products_table = $wpdb->prefix . 'price_comparison_products';
$products_sql = "CREATE TABLE IF NOT EXISTS $products_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
product_name varchar(255) NOT NULL,
description text,
category varchar(100),
image_url varchar(500),
created_at datetime DEFAULT CURRENT_TIMESTAMP,
updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) $charset_collate;";
// 价格信息表
$prices_table = $wpdb->prefix . 'price_comparison_prices';
$prices_sql = "CREATE TABLE IF NOT EXISTS $prices_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
product_id mediumint(9) NOT NULL,
merchant_name varchar(100) NOT NULL,
price decimal(10,2) NOT NULL,
original_price decimal(10,2),
currency varchar(10) DEFAULT 'CNY',
product_url varchar(500),
availability tinyint(1) DEFAULT 1,
last_updated datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY product_id (product_id),
KEY merchant_name (merchant_name)
) $charset_collate;";
// 优惠券信息表
$coupons_table = $wpdb->prefix . 'price_comparison_coupons';
$coupons_sql = "CREATE TABLE IF NOT EXISTS $coupons_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
merchant_name varchar(100) NOT NULL,
coupon_code varchar(100),
coupon_description text,
discount_value varchar(100),
discount_type varchar(50),
expiry_date date,
terms_conditions text,
product_category varchar(100),
is_active tinyint(1) DEFAULT 1,
click_count mediumint(9) DEFAULT 0,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY merchant_name (merchant_name),
KEY expiry_date (expiry_date),
KEY is_active (is_active)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($products_sql);
dbDelta($prices_sql);
dbDelta($coupons_sql);
}
// 在插件激活时创建表
register_activation_hook(__FILE__, 'create_price_comparison_tables');
2.2 添加数据库更新钩子
为了确保数据库表在主题激活时创建,添加以下代码:
// 主题激活时创建表
add_action('after_switch_theme', 'create_price_comparison_tables');
// 添加数据库版本控制
$price_comparison_db_version = '1.0';
function update_price_comparison_tables() {
global $price_comparison_db_version;
$installed_version = get_option('price_comparison_db_version');
if ($installed_version != $price_comparison_db_version) {
create_price_comparison_tables();
update_option('price_comparison_db_version', $price_comparison_db_version);
}
}
add_action('init', 'update_price_comparison_tables');
第三部分:构建数据采集系统
3.1 设计API接口类
我们需要创建一个类来处理与各大电商平台API的交互。在子主题目录下创建includes/class-price-api-manager.php:
<?php
if (!defined('ABSPATH')) {
exit;
}
class Price_API_Manager {
private $api_keys = array();
public function __construct() {
// 从WordPress选项获取API密钥
$this->api_keys = get_option('price_comparison_api_keys', array());
}
/**
* 从京东获取商品信息
*/
public function fetch_jd_product($keyword, $category = '') {
$api_url = 'https://api.jd.com/routerjson';
$params = array(
'method' => 'jingdong.ware.search',
'app_key' => isset($this->api_keys['jd_app_key']) ? $this->api_keys['jd_app_key'] : '',
'timestamp' => date('Y-m-d H:i:s'),
'format' => 'json',
'v' => '2.0',
'sign_method' => 'md5',
'param_json' => json_encode(array(
'keyword' => $keyword,
'catId' => $category,
'page' => 1,
'pageSize' => 20
))
);
// 生成签名(简化版,实际需要按照京东API文档实现)
$params['sign'] = $this->generate_jd_signature($params);
$response = wp_remote_get($api_url . '?' . http_build_query($params));
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
return $this->parse_jd_response($data);
}
/**
* 从淘宝/天猫获取商品信息
*/
public function fetch_taobao_product($keyword, $category = '') {
// 使用淘宝开放平台API
// 注意:需要申请正式API权限
$api_url = 'https://eco.taobao.com/router/rest';
$params = array(
'method' => 'taobao.tbk.item.get',
'app_key' => isset($this->api_keys['taobao_app_key']) ? $this->api_keys['taobao_app_key'] : '',
'timestamp' => date('Y-m-d H:i:s'),
'format' => 'json',
'v' => '2.0',
'sign_method' => 'md5',
'q' => $keyword,
'cat' => $category,
'page_no' => 1,
'page_size' => 20
);
$params['sign'] = $this->generate_taobao_signature($params);
$response = wp_remote_get($api_url . '?' . http_build_query($params));
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
return $this->parse_taobao_response($data);
}
/**
* 从拼多多获取商品信息
*/
public function fetch_pdd_product($keyword) {
// 拼多多联盟API
$api_url = 'https://gw-api.pinduoduo.com/api/router';
$params = array(
'type' => 'pdd.ddk.goods.search',
'client_id' => isset($this->api_keys['pdd_client_id']) ? $this->api_keys['pdd_client_id'] : '',
'timestamp' => time(),
'data_type' => 'JSON',
'keyword' => $keyword,
'page' => 1,
'page_size' => 20
);
$params['sign'] = $this->generate_pdd_signature($params);
$response = wp_remote_post($api_url, array(
'body' => json_encode($params),
'headers' => array('Content-Type' => 'application/json')
));
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
return $this->parse_pdd_response($data);
}
/**
* 获取优惠券信息
*/
public function fetch_coupons($merchant = '', $category = '') {
$coupons = array();
// 这里可以集成多个优惠券API
// 例如:淘宝客优惠券、京东优惠券等
// 示例:从本地数据库获取优惠券
global $wpdb;
$table_name = $wpdb->prefix . 'price_comparison_coupons';
$query = "SELECT * FROM $table_name WHERE is_active = 1";
if (!empty($merchant)) {
$query .= $wpdb->prepare(" AND merchant_name = %s", $merchant);
}
if (!empty($category)) {
$query .= $wpdb->prepare(" AND product_category = %s", $category);
}
$query .= " AND (expiry_date IS NULL OR expiry_date >= CURDATE()) ORDER BY created_at DESC LIMIT 50";
$coupons = $wpdb->get_results($query, ARRAY_A);
return $coupons;
}
// 以下为辅助方法,实际开发中需要完整实现
private function generate_jd_signature($params) {
// 实现京东签名算法
return md5(implode('', $params) . (isset($this->api_keys['jd_app_secret']) ? $this->api_keys['jd_app_secret'] : ''));
}
private function generate_taobao_signature($params) {
// 实现淘宝签名算法
return md5(implode('', $params) . (isset($this->api_keys['taobao_app_secret']) ? $this->api_keys['taobao_app_secret'] : ''));
}
private function generate_pdd_signature($params) {
// 实现拼多多签名算法
return md5(implode('', $params) . (isset($this->api_keys['pdd_client_secret']) ? $this->api_keys['pdd_client_secret'] : ''));
}
private function parse_jd_response($data) {
// 解析京东API响应
if (!isset($data['code']) || $data['code'] != '0') {
return array();
}
$products = array();
// 解析逻辑...
return $products;
}
private function parse_taobao_response($data) {
// 解析淘宝API响应
if (!isset($data['error_response'])) {
return array();
}
$products = array();
// 解析逻辑...
return $products;
}
private function parse_pdd_response($data) {
// 解析拼多多API响应
if (!isset($data['error_response'])) {
return array();
}
$products = array();
// 解析逻辑...
return $products;
}
}
?>
3.2 创建数据采集调度器
为了定期更新价格和优惠券信息,我们需要创建一个调度器。创建includes/class-data-collector.php:
<?php
if (!defined('ABSPATH')) {
exit;
}
class Price_Data_Collector {
private $api_manager;
public function __construct() {
$this->api_manager = new Price_API_Manager();
// 设置定时任务
add_action('price_comparison_daily_cron', array($this, 'daily_data_collection'));
add_action('price_comparison_hourly_cron', array($this, 'hourly_price_check'));
// 初始化定时任务
$this->schedule_cron_jobs();
}
/**
* 安排定时任务
*/
private function schedule_cron_jobs() {
if (!wp_next_scheduled('price_comparison_daily_cron')) {
wp_schedule_event(time(), 'daily', 'price_comparison_daily_cron');
}
if (!wp_next_scheduled('price_comparison_hourly_cron')) {
wp_schedule_event(time(), 'hourly', 'price_comparison_hourly_cron');
}
}
/**
* 每日数据收集
*/
public function daily_data_collection() {
global $wpdb;
// 收集热门商品的价格信息
$popular_products = $this->get_popular_products();
foreach ($popular_products as $product) {
$this->update_product_prices($product['product_name'], $product['category']);
}
// 更新优惠券信息
$this->update_coupon_data();
// 清理过期数据
$this->cleanup_old_data();
}
/**
* 每小时价格检查
*/
public function hourly_price_check() {
// 检查价格变动,特别是促销商品
$promotional_products = $this->get_promotional_products();
foreach ($promotional_products as $product) {
$this->check_price_changes($product['id']);
}
}
/**
* 更新商品价格
*/
private function update_product_prices($product_name, $category = '') {
// 从多个平台获取价格
$jd_prices = $this->api_manager->fetch_jd_product($product_name, $category);
$taobao_prices = $this->api_manager->fetch_taobao_product($product_name, $category);
$pdd_prices = $this->api_manager->fetch_pdd_product($product_name);
// 合并价格数据
$all_prices = array_merge(
$this->format_prices($jd_prices, '京东'),
$this->format_prices($taobao_prices, '淘宝'),
$this->format_prices($pdd_prices, '拼多多')
);
// 保存到数据库
$this->save_prices_to_db($product_name, $all_prices);
}
/**
* 更新优惠券数据
*/
private function update_coupon_data() {
// 从各平台API获取最新优惠券
$coupons = $this->api_manager->fetch_coupons();
// 保存到数据库
$this->save_coupons_to_db($coupons);
}
/**
* 获取热门商品
*/
private function get_popular_products() {
global $wpdb;
$products_table = $wpdb->prefix . 'price_comparison_products';
// 获取最近30天有搜索或点击的商品
$query = "SELECT * FROM $products_table
WHERE updated_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
ORDER BY (SELECT COUNT(*) FROM {$wpdb->prefix}price_comparison_prices
WHERE product_id = $products_table.id) DESC
LIMIT 50";
return $wpdb->get_results($query, ARRAY_A);
}
/**
* 获取促销商品
*/
private function get_promotional_products() {
global $wpdb;
$prices_table = $wpdb->prefix . 'price_comparison_prices';
// 获取最近有价格变动的商品
$query = "SELECT DISTINCT product_id as id FROM $prices_table
WHERE last_updated >= DATE_SUB(NOW(), INTERVAL 7 DAY)
AND original_price > price
LIMIT 20";
return $wpdb->get_results($query, ARRAY_A);
}
/**
* 检查价格变动
*/
private function check_price_changes($product_id) {
global $wpdb;
$prices_table = $wpdb->prefix . 'price_comparison_prices';
// 获取商品当前价格
$current_prices = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM $prices_table WHERE product_id = %d", $product_id),
A
);
// 重新从API获取最新价格
$product_info = $wpdb->get_row(
$wpdb->prepare("SELECT * FROM {$wpdb->prefix}price_comparison_products WHERE id = %d", $product_id),
ARRAY_A
);
if ($product_info) {
$new_prices = $this->api_manager->fetch_jd_product($product_info['product_name'], $product_info['category']);
// 比较价格变动
foreach ($current_prices as $current) {
foreach ($new_prices as $new) {
if ($current['merchant_name'] == $new['merchant']) {
if ($current['price'] != $new['price']) {
// 价格变动,记录并可能发送通知
$this->record_price_change($product_id, $current, $new);
}
}
}
}
}
}
/**
* 格式化价格数据
*/
private function format_prices($prices, $merchant) {
$formatted = array();
if (is_array($prices)) {
foreach ($prices as $price) {
$formatted[] = array(
'merchant' => $merchant,
'price' => $price['price'] ?? 0,
'original_price' => $price['original_price'] ?? $price['price'],
'product_url' => $price['url'] ?? '',
'availability' => $price['availability'] ?? 1
);
}
}
return $formatted;
}
/**
* 保存价格到数据库
*/
private function save_prices_to_db($product_name, $prices) {
global $wpdb;
$products_table = $wpdb->prefix . 'price_comparison_products';
$prices_table = $wpdb->prefix . 'price_comparison_prices';
// 查找或创建商品记录
$product = $wpdb->get_row(
$wpdb->prepare("SELECT id FROM $products_table WHERE product_name = %s", $product_name),
ARRAY_A
);
if (!$product) {
$wpdb->insert($products_table, array(
'product_name' => $product_name,
'created_at' => current_time('mysql')
));
$product_id = $wpdb->insert_id;
} else {
$product_id = $product['id'];
}
// 保存价格信息
foreach ($prices as $price) {
$existing = $wpdb->get_row(
$wpdb->prepare(
"SELECT id FROM $prices_table WHERE product_id = %d AND merchant_name = %s",
$product_id,
$price['merchant']
),
ARRAY_A
);
if ($existing) {
// 更新现有记录
$wpdb->update($prices_table, array(
'price' => $price['price'],
'original_price' => $price['original_price'],
'product_url' => $price['product_url'],
'availability' => $price['availability'],
'last_updated' => current_time('mysql')
), array('id' => $existing['id']));
} else {
// 插入新记录
$wpdb->insert($prices_table, array(
'product_id' => $product_id,
'merchant_name' => $price['merchant'],
'price' => $price['price'],
'original_price' => $price['original_price'],
'product_url' => $price['product_url'],
'availability' => $price['availability'],
'last_updated' => current_time('mysql')
));
}
}
}
/**
* 保存优惠券到数据库
*/
private function save_coupons_to_db($coupons) {
global $wpdb;
$coupons_table = $wpdb->prefix . 'price_comparison_coupons';
foreach ($coupons as $coupon) {
// 检查是否已存在相同优惠券
$existing = $wpdb->get_row(
$wpdb->prepare(
"SELECT id FROM $coupons_table WHERE merchant_name = %s AND coupon_code = %s",
$coupon['merchant_name'],
$coupon['coupon_code']
),
ARRAY_A
);
if (!$existing) {
$wpdb->insert($coupons_table, $coupon);
}
}
}
/**
* 记录价格变动
*/
private function record_price_change($product_id, $old_price, $new_price) {
global $wpdb;
$changes_table = $wpdb->prefix . 'price_comparison_changes';
// 创建价格变动记录表(如果不存在)
if ($wpdb->get_var("SHOW TABLES LIKE '$changes_table'") != $changes_table) {
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $changes_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
product_id mediumint(9) NOT NULL,
merchant_name varchar(100) NOT NULL,
old_price decimal(10,2) NOT NULL,
new_price decimal(10,2) NOT NULL,
change_percent decimal(5,2),
change_type varchar(20),
recorded_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
// 计算变动百分比
$change_percent = (($new_price['price'] - $old_price['price']) / $old_price['price']) * 100;
$change_type = $new_price['price'] < $old_price['price'] ? '降价' : '涨价';
// 插入变动记录
$wpdb->insert($changes_table, array(
'product_id' => $product_id,
'merchant_name' => $old_price['merchant_name'],
'old_price' => $old_price['price'],
'new_price' => $new_price['price'],
'change_percent' => $change_percent,
'change_type' => $change_type,
'recorded_at' => current_time('mysql')
));
// 可以在这里添加邮件通知或站内通知逻辑
$this->notify_price_change($product_id, $old_price, $new_price, $change_percent, $change_type);
}
/**
* 通知价格变动
*/
private function notify_price_change($product_id, $old_price, $new_price, $change_percent, $change_type) {
// 获取关注此商品的用户
$followers = $this->get_product_followers($product_id);
if (!empty($followers)) {
$product_info = $wpdb->get_row(
$wpdb->prepare("SELECT product_name FROM {$wpdb->prefix}price_comparison_products WHERE id = %d", $product_id),
ARRAY_A
);
foreach ($followers as $follower) {
// 发送邮件通知
$subject = "价格变动通知:{$product_info['product_name']} {$change_type}了" . abs($change_percent) . "%";
$message = "商品:{$product_info['product_name']}n";
$message .= "商家:{$old_price['merchant_name']}n";
$message .= "原价:{$old_price['price']}元n";
$message .= "现价:{$new_price['price']}元n";
$message .= "变动幅度:{$change_percent}%n";
$message .= "查看详情:" . home_url("/product/{$product_id}");
wp_mail($follower['email'], $subject, $message);
}
}
}
/**
* 清理旧数据
*/
private function cleanup_old_data() {
global $wpdb;
$prices_table = $wpdb->prefix . 'price_comparison_prices';
$coupons_table = $wpdb->prefix . 'price_comparison_coupons';
// 删除30天前的价格记录(保留最新记录)
$wpdb->query(
"DELETE FROM $prices_table
WHERE last_updated < DATE_SUB(NOW(), INTERVAL 30 DAY)
AND id NOT IN (
SELECT id FROM (
SELECT MAX(id) as id
FROM $prices_table
GROUP BY product_id, merchant_name
) as latest
)"
);
// 标记过期优惠券为无效
$wpdb->query(
"UPDATE $coupons_table
SET is_active = 0
WHERE expiry_date < CURDATE() AND is_active = 1"
);
}
}
?>
## 第四部分:创建管理界面
### 4.1 添加WordPress管理菜单
在`functions.php`中添加管理菜单:
// 添加管理菜单
function price_comparison_admin_menu() {
add_menu_page(
'比价与优惠券管理',
'比价管理',
'manage_options',
'price-comparison',
'price_comparison_admin_page',
'dashicons-chart-line',
30
);
add_submenu_page(
'price-comparison',
'商品管理',
'商品管理',
'manage_options',
'price-comparison-products',
'price_comparison_products_page'
);
add_submenu_page(
'price-comparison',
'价格监控',
'价格监控',
'manage_options',
'price-comparison-monitor',
'price_comparison_monitor_page'
);
add_submenu_page(
'price-comparison',
'优惠券管理',
'优惠券管理',
'manage_options',
'price-comparison-coupons',
'price_comparison_coupons_page'
);
add_submenu_page(
'price-comparison',
'API设置',
'API设置',
'manage_options',
'price-comparison-settings',
'price_comparison_settings_page'
);
}
add_action('admin_menu', 'price_comparison_admin_menu');
// 主管理页面
function price_comparison_admin_page() {
?>
<div class="wrap">
<h1>比价与优惠券管理系统</h1>
<div class="price-comparison-dashboard">
<div class="dashboard-card">
<h3>商品总数</h3>
<p class="dashboard-number"><?php echo get_product_count(); ?></p>
</div>
<div class="dashboard-card">
<h3>有效优惠券</h3>
<p class="dashboard-number"><?php echo get_active_coupon_count(); ?></p>
</div>
<div class="dashboard-card">
<h3>今日价格更新</h3>
<p class="dashboard-number"><?php echo get_today_price_updates(); ?></p>
</div>
<div class="dashboard-card">
<h3>用户搜索量</h3>
<p class="dashboard-number"><?php echo get_today_searches(); ?></p>
</div>
</div>
<div class="recent-activity">
<h2>最近活动</h2>
<?php display_recent_activity(); ?>
</div>
</div>
<style>
.price-comparison-dashboard {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
margin: 20px 0;
}
.dashboard-card {
background: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
text-align: center;
}
.dashboard-number {
font-size: 2em;
font-weight: bold;
color: #0073aa;
margin: 10px 0;
}
</style>
<?php
}
// 商品管理页面
function price_comparison_products_page() {
global $wpdb;
// 处理表单提交
if (isset($_POST['add_product'])) {
$product_name = sanitize_text_field($_POST['product_name']);
$category = sanitize_text_field($_POST['category']);
$wpdb->insert(
$wpdb->prefix . 'price_comparison_products',
array(
'product_name' => $product_name,
'category' => $category,
'created_at' => current_time('mysql')
)
);
echo '<div class="notice notice-success"><p>商品添加成功!</p></div>';
}
// 获取商品列表
$products = $wpdb->get_results(
"SELECT * FROM {$wpdb->prefix}price_comparison_products ORDER BY created_at DESC LIMIT 50",
ARRAY_A
);
?>
<div class="wrap">
<h1>商品管理</h1>
<div class="add-product-form">
<h2>添加新商品</h2>
<form method="post">
<table class="form-table">
<tr>
<th><label for="product_name">商品名称</label></th>
<td><input type="text" id="product_name" name="product_name" class="regular-text" required></td>
</tr>
<tr>
<th><label for="category">商品分类</label></th>
<td>
<input type="text" id="category" name="category" class="regular-text">
<p class="description">例如:手机、笔记本电脑、家电等</p>
</td>
</tr>
</table>
<?php submit_button('添加商品', 'primary', 'add_product'); ?>
</form>
</div>
<div class="product-list">
<h2>商品列表</h2>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>ID</th>
<th>商品名称</th>
<th>分类</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td><?php echo $product['id']; ?></td>
<td><?php echo esc_html($product['product_name']); ?></td>
<td><?php echo esc_html($product['category']); ?></td>
<td><?php echo $product['created_at']; ?></td>
<td>
<a href="<?php echo admin_url('admin.php?page=price-comparison-monitor&product_id=' . $product['id']); ?>">查看价格</a> |
<a href="#" class="delete-product" data-id="<?php echo $product['id']; ?>">删除</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<script>
jQuery(document).ready(function($) {
$('.delete-product').click(function(e) {
e.preventDefault();
if (confirm('确定要删除这个商品吗?')) {
var productId = $(this).data('id');
$.post(ajaxurl, {
action: 'delete_product',
product_id: productId,
nonce: '<?php echo wp_create_nonce('delete_product_nonce'); ?>'
}, function(response) {
if (response.success) {
location.reload();
} else {
alert('删除失败:' + response.data);
}
});
}
});
});
</script>
<?php
}
// 价格监控页面
function price_comparison_monitor_page() {
global $wpdb;
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : 0;
if ($product_id) {
// 显示单个商品的价格信息
$product = $wpdb->get_row(
$wpdb->prepare("SELECT * FROM {$wpdb->prefix}price_comparison_products WHERE id = %d", $product_id),
ARRAY_A
);
$prices = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}price_comparison_prices WHERE product_id = %d ORDER BY price ASC",
$product_id
),
ARRAY_A
);
?>
<div class="wrap">
<h1>价格监控:<?php echo esc_html($product['product_name']); ?></h1>
<div class="price-comparison-chart">
<canvas id="priceHistoryChart" width="800" height="400"></canvas>
</div>
<div class="current-prices">
<h2>当前价格对比</h2>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>商家</th>
<th>当前价格</th>
<th>原价</th>
<th>优惠幅度</th>
<th>最后更新</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($prices as $price): ?>
<tr>
<td><?php echo esc_html($price['merchant_name']); ?></td>
<td><strong style="color: #d63638;"><?php echo $price['price']; ?>元</strong></td>
<td><del><?php echo $price['original_price']; ?>元</del></td>
<td>
<?php if ($price['original_price'] > $price['price']): ?>
<span class="discount-badge">
-<?php echo round((($price['original_price'] - $price['price']) /
