文章目录
-
- 在当今数字化时代,随着全球数据保护法规的不断完善,网站隐私合规性已成为每个网站所有者必须面对的重要课题。从欧盟的《通用数据保护条例》(GDPR)到加州的《消费者隐私法案》(CCPA),再到中国的《个人信息保护法》,全球各地都在加强对用户隐私的保护。对于使用WordPress构建的网站而言,如何有效管理Cookie和获取用户隐私同意,不仅是一项法律义务,更是建立用户信任的关键。 本教程将深入探讨如何通过WordPress代码二次开发,实现专业的Cookie合规性管理与用户隐私同意控件,同时集成常用互联网小工具功能。我们将从基础概念入手,逐步深入到具体实现,为您提供一套完整、实用的解决方案。
-
- Cookie合规性指的是网站在使用Cookie和其他跟踪技术时,必须遵守相关隐私法规的要求。这主要包括: 知情同意原则:在设置非必要Cookie前,必须获得用户的明确同意 透明度原则:清晰告知用户网站使用了哪些Cookie及其目的 控制权原则:允许用户随时撤回同意或调整Cookie偏好 数据最小化原则:只收集实现特定目的所需的最少数据
- GDPR(欧盟通用数据保护条例):适用于处理欧盟公民数据的任何组织,无论其所在地 CCPA(加州消费者隐私法案):保护加州居民的个人信息权利 PIPL(中国个人信息保护法):规范在中国境内处理个人信息的活动 ePrivacy指令:专门规范电子通信隐私,包括Cookie使用
- WordPress作为内容管理系统,本身及其插件、主题都可能设置各种Cookie。常见的包括: 会话Cookie(用于用户登录状态) 评论功能Cookie 统计分析Cookie(如Google Analytics) 社交媒体集成Cookie 广告跟踪Cookie
-
- 一个完整的Cookie合规解决方案应包含以下核心功能: Cookie横幅/弹出窗口:首次访问时显示,请求用户同意 Cookie偏好中心:允许用户详细管理各类Cookie 同意记录与证明:存储用户同意状态,以便审计 脚本加载控制:根据用户同意状态有条件加载第三方脚本 自动阻止功能:在获得同意前阻止非必要Cookie 定期重新同意:根据法规要求定期更新用户同意
- 我们将采用模块化设计,创建以下核心组件: 主控制器类:协调所有功能模块 前端展示模块:处理横幅和偏好中心的UI 同意管理模块:存储和管理用户同意状态 脚本控制模块:根据同意状态控制第三方脚本加载 设置管理模块:提供后台配置界面 小工具集成模块:扩展常用互联网工具功能
- 我们需要创建数据库表来存储: 用户同意记录 Cookie分类和描述 第三方服务配置 同意历史记录
-
- 在开始编码前,请确保您已准备好: 本地WordPress开发环境:可以使用Local by Flywheel、XAMPP或Docker 代码编辑器:推荐VS Code、PHPStorm或Sublime Text 浏览器开发者工具:用于调试前端代码 Git版本控制系统:管理代码变更
- 我们将创建一个独立的WordPress插件来实现所有功能: <?php /** * Plugin Name: Advanced Cookie Consent Manager * Plugin URI: https://yourwebsite.com/ * Description: 完整的Cookie合规性与隐私同意管理解决方案 * Version: 1.0.0 * Author: Your Name * License: GPL v2 or later * Text Domain: advanced-cookie-consent */ // 防止直接访问 if (!defined('ABSPATH')) { exit; } // 定义插件常量 define('ACCM_VERSION', '1.0.0'); define('ACCM_PLUGIN_DIR', plugin_dir_path(__FILE__)); define('ACCM_PLUGIN_URL', plugin_dir_url(__FILE__)); define('ACCM_PLUGIN_BASENAME', plugin_basename(__FILE__));
- 创建以下目录结构: advanced-cookie-consent/ ├── includes/ │ ├── class-main-controller.php │ ├── class-frontend-ui.php │ ├── class-consent-manager.php │ ├── class-script-controller.php │ ├── class-settings-manager.php │ └── class-widget-integration.php ├── assets/ │ ├── css/ │ │ ├── frontend.css │ │ └── admin.css │ ├── js/ │ │ ├── frontend.js │ │ └── admin.js │ └── images/ ├── languages/ ├── templates/ │ ├── cookie-banner.php │ └── preference-center.php └── advanced-cookie-consent.php
-
- <?php // includes/class-main-controller.php class ACCM_Main_Controller { private static $instance = null; private $frontend_ui; private $consent_manager; private $script_controller; private $settings_manager; private $widget_integration; public static function get_instance() { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } private function __construct() { $this->load_dependencies(); $this->init_hooks(); } private function load_dependencies() { require_once ACCM_PLUGIN_DIR . 'includes/class-frontend-ui.php'; require_once ACCM_PLUGIN_DIR . 'includes/class-consent-manager.php'; require_once ACCM_PLUGIN_DIR . 'includes/class-script-controller.php'; require_once ACCM_PLUGIN_DIR . 'includes/class-settings-manager.php'; require_once ACCM_PLUGIN_DIR . 'includes/class-widget-integration.php'; $this->frontend_ui = new ACCM_Frontend_UI(); $this->consent_manager = new ACCM_Consent_Manager(); $this->script_controller = new ACCM_Script_Controller(); $this->settings_manager = new ACCM_Settings_Manager(); $this->widget_integration = new ACCM_Widget_Integration(); } private function init_hooks() { // 激活/停用插件钩子 register_activation_hook(__FILE__, array($this, 'activate_plugin')); register_deactivation_hook(__FILE__, array($this, 'deactivate_plugin')); // 初始化钩子 add_action('init', array($this, 'init')); // 管理界面钩子 add_action('admin_menu', array($this->settings_manager, 'add_admin_menu')); add_action('admin_init', array($this->settings_manager, 'register_settings')); // 前端钩子 add_action('wp_enqueue_scripts', array($this->frontend_ui, 'enqueue_assets')); add_action('wp_footer', array($this->frontend_ui, 'render_cookie_banner')); // 脚本控制钩子 add_action('wp_head', array($this->script_controller, 'add_script_control_scripts'), 1); } public function init() { // 加载文本域 load_plugin_textdomain('advanced-cookie-consent', false, dirname(ACCM_PLUGIN_BASENAME) . '/languages'); // 初始化组件 $this->consent_manager->init(); $this->widget_integration->init(); } public function activate_plugin() { // 创建数据库表 $this->consent_manager->create_tables(); // 设置默认选项 $this->settings_manager->set_default_options(); // 刷新重写规则 flush_rewrite_rules(); } public function deactivate_plugin() { // 清理临时数据 flush_rewrite_rules(); } }
- <?php // includes/class-frontend-ui.php class ACCM_Frontend_UI { private $consent_manager; public function __construct() { $this->consent_manager = ACCM_Consent_Manager::get_instance(); } public function enqueue_assets() { // 前端样式 wp_enqueue_style( 'accm-frontend-style', ACCM_PLUGIN_URL . 'assets/css/frontend.css', array(), ACCM_VERSION ); // 前端脚本 wp_enqueue_script( 'accm-frontend-script', ACCM_PLUGIN_URL . 'assets/js/frontend.js', array('jquery'), ACCM_VERSION, true ); // 本地化脚本 wp_localize_script('accm-frontend-script', 'accm_ajax', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('accm_nonce'), 'consent_categories' => $this->consent_manager->get_cookie_categories(), 'strings' => array( 'saving' => __('保存中...', 'advanced-cookie-consent'), 'saved' => __('设置已保存', 'advanced-cookie-consent'), 'error' => __('保存时出错,请重试', 'advanced-cookie-consent') ) )); } public function render_cookie_banner() { // 检查是否已获得同意 if ($this->consent_manager->has_consent()) { return; } // 获取设置 $settings = get_option('accm_settings', array()); // 包含横幅模板 include ACCM_PLUGIN_DIR . 'templates/cookie-banner.php'; } public function render_preference_center() { // 获取Cookie分类 $categories = $this->consent_manager->get_cookie_categories(); // 获取用户当前偏好 $user_preferences = $this->consent_manager->get_user_preferences(); // 包含偏好中心模板 include ACCM_PLUGIN_DIR . 'templates/preference-center.php'; } }
- <?php // templates/cookie-banner.php $settings = get_option('accm_settings', array()); $banner_title = isset($settings['banner_title']) ? $settings['banner_title'] : __('Cookie设置', 'advanced-cookie-consent'); $banner_text = isset($settings['banner_text']) ? $settings['banner_text'] : __('我们使用Cookie来提升您的浏览体验,提供个性化内容并分析流量。点击"接受"即表示您同意我们使用所有Cookie。', 'advanced-cookie-consent'); $accept_text = isset($settings['accept_text']) ? $settings['accept_text'] : __('接受所有', 'advanced-cookie-consent'); $reject_text = isset($settings['reject_text']) ? $settings['reject_text'] : __('拒绝非必要', 'advanced-cookie-consent'); $preferences_text = isset($settings['preferences_text']) ? $settings['preferences_text'] : __('自定义设置', 'advanced-cookie-consent'); $privacy_policy_url = isset($settings['privacy_policy_url']) ? $settings['privacy_policy_url'] : get_privacy_policy_url(); $privacy_policy_text = isset($settings['privacy_policy_text']) ? $settings['privacy_policy_text'] : __('隐私政策', 'advanced-cookie-consent'); ?> <div id="accm-cookie-banner" class="accm-cookie-banner" style="display: none;"> <div class="accm-banner-content"> <div class="accm-banner-text"> <h3><?php echo esc_html($banner_title); ?></h3> <p><?php echo esc_html($banner_text); ?></p> <?php if ($privacy_policy_url): ?> <p class="accm-privacy-link"> <a href="<?php echo esc_url($privacy_policy_url); ?>" target="_blank"> <?php echo esc_html($privacy_policy_text); ?> </a> </p> <?php endif; ?> </div> <div class="accm-banner-buttons"> <button type="button" class="accm-btn accm-btn-preferences"> <?php echo esc_html($preferences_text); ?> </button> <button type="button" class="accm-btn accm-btn-reject"> <?php echo esc_html($reject_text); ?> </button> <button type="button" class="accm-btn accm-btn-accept accm-btn-primary"> <?php echo esc_html($accept_text); ?> </button> </div> </div> </div> <div id="accm-preference-modal" class="accm-modal" style="display: none;"> <div class="accm-modal-content"> <div class="accm-modal-header"> <h3><?php _e('Cookie偏好设置', 'advanced-cookie-consent'); ?></h3> <button type="button" class="accm-modal-close">×</button> </div> <div class="accm-modal-body"> <?php $this->render_preference_center(); ?> </div> <div class="accm-modal-footer"> <button type="button" class="accm-btn accm-btn-save-preferences accm-btn-primary"> <?php _e('保存设置', 'advanced-cookie-consent'); ?> </button> </div> </div> </div>
- <?php // includes/class-consent-manager.php class ACCM_Consent_Manager { private static $instance = null; private $cookie_name = 'accm_consent'; private $cookie_expiry = 365; // 天数 public static function get_instance() { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } public function init() { // 处理AJAX请求 add_action('wp_ajax_accm_save_consent', array($this, 'ajax_save_consent')); add_action('wp_ajax_nopriv_accm_save_consent', array($this, 'ajax_save_consent')); // 检查并处理Cookie同意 $this->check_consent_cookie(); } public function create_tables() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name = $wpdb->prefix . 'accm_consent_logs'; $sql = "CREATE TABLE IF NOT EXISTS $table_name ( id bigint(20) NOT NULL AUTO_INCREMENT, consent_id varchar(32) NOT NULL, user_id bigint(20) DEFAULT 0, user_ip varchar(45) DEFAULT '', user_agent text, consent_data text NOT NULL, consent_date datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY consent_id (consent_id), KEY user_id (user_id), KEY consent_date (consent_date) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } public function get_cookie_categories() { $default_categories = array( 'necessary' => array( 'name' => __('必要', 'advanced-cookie-consent'), 'description' => __('这些Cookie对于网站的基本功能是必需的,无法关闭。', 'advanced-cookie-consent'), 'required' => true, 'default' => true ), 'preferences' => array( 'name' => __('偏好设置', 'advanced-cookie-consent'), 'description' => __('这些Cookie允许网站记住您的选择和偏好。', 'advanced-cookie-consent'), 'required' => false, 'default' => true ), 'analytics' => array( 'name' => __('统计分析', 'advanced-cookie-consent'), 'description' => __('这些Cookie帮助我们了解访问者如何与网站互动。', 'advanced-cookie-consent'), 'required' => false, 'default' => true ), 'marketing' => array( 'name' => __('营销', 'advanced-cookie-consent'), 'description' => __('这些Cookie用于跟踪广告效果和个性化广告。', 'advanced-cookie-consent'), 'required' => false, 'default' => false ) ); // 允许通过过滤器添加或修改分类 return apply_filters('accm_cookie_categories', $default_categories); } public function has_consent($category = '') { $consent_data = $this->get_consent_data(); if (empty($consent_data)) { return false; } if (empty($category)) { return !empty($consent_data); } $categories = $this->get_cookie_categories(); if (!isset($categories[$category])) { return false; } // 必要Cookie始终视为已同意
-
-
- <?php // includes/class-consent-manager.php(续) if ($categories[$category]['required']) { return true; } return isset($consent_data[$category]) && $consent_data[$category] === true; } private function get_consent_data() { static $consent_data = null; if ($consent_data !== null) { return $consent_data; } // 首先检查Cookie if (isset($_COOKIE[$this->cookie_name])) { $cookie_data = json_decode(stripslashes($_COOKIE[$this->cookie_name]), true); if (is_array($cookie_data)) { $consent_data = $cookie_data; return $consent_data; } } // 如果没有Cookie,检查默认设置 $settings = get_option('accm_settings', array()); $default_consent = isset($settings['default_consent']) ? $settings['default_consent'] : 'none'; if ($default_consent === 'all') { $categories = $this->get_cookie_categories(); $consent_data = array(); foreach ($categories as $key => $category) { $consent_data[$key] = true; } } else { $consent_data = array(); } return $consent_data; } public function get_user_preferences() { $consent_data = $this->get_consent_data(); $categories = $this->get_cookie_categories(); $preferences = array(); foreach ($categories as $key => $category) { $preferences[$key] = array( 'name' => $category['name'], 'description' => $category['description'], 'required' => $category['required'], 'enabled' => $this->has_consent($key) ); } return $preferences; } public function ajax_save_consent() { // 验证nonce if (!check_ajax_referer('accm_nonce', 'nonce', false)) { wp_die(json_encode(array( 'success' => false, 'message' => __('安全验证失败', 'advanced-cookie-consent') ))); } // 获取并验证数据 $consent_data = isset($_POST['consent_data']) ? $_POST['consent_data'] : array(); if (!is_array($consent_data)) { wp_die(json_encode(array( 'success' => false, 'message' => __('无效的数据格式', 'advanced-cookie-consent') ))); } // 验证分类 $categories = $this->get_cookie_categories(); $validated_data = array(); foreach ($categories as $key => $category) { if ($category['required']) { $validated_data[$key] = true; } else { $validated_data[$key] = isset($consent_data[$key]) && $consent_data[$key] === 'true'; } } // 生成唯一ID $consent_id = wp_generate_uuid4(); // 记录同意 $this->log_consent($consent_id, $validated_data); // 设置Cookie $this->set_consent_cookie($consent_id, $validated_data); // 返回成功响应 wp_die(json_encode(array( 'success' => true, 'message' => __('设置已保存', 'advanced-cookie-consent'), 'consent_id' => $consent_id ))); } private function log_consent($consent_id, $consent_data) { global $wpdb; $table_name = $wpdb->prefix . 'accm_consent_logs'; $user_id = get_current_user_id(); $user_ip = $this->get_user_ip(); $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; $wpdb->insert( $table_name, array( 'consent_id' => $consent_id, 'user_id' => $user_id, 'user_ip' => $user_ip, 'user_agent' => $user_agent, 'consent_data' => json_encode($consent_data) ), array('%s', '%d', '%s', '%s', '%s') ); } private function set_consent_cookie($consent_id, $consent_data) { $cookie_data = array( 'consent_id' => $consent_id, 'categories' => $consent_data, 'timestamp' => time() ); $cookie_value = json_encode($cookie_data); // 设置Cookie setcookie( $this->cookie_name, $cookie_value, time() + ($this->cookie_expiry * DAY_IN_SECONDS), COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true // HttpOnly ); // 立即在本次请求中可用 $_COOKIE[$this->cookie_name] = $cookie_value; } private function get_user_ip() { $ip = ''; if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : ''; } private function check_consent_cookie() { // 检查Cookie是否需要更新 if (isset($_COOKIE[$this->cookie_name])) { $cookie_data = json_decode(stripslashes($_COOKIE[$this->cookie_name]), true); if (is_array($cookie_data) && isset($cookie_data['timestamp'])) { $cookie_age = time() - $cookie_data['timestamp']; $renewal_period = 365 * DAY_IN_SECONDS; // 一年后重新请求同意 if ($cookie_age > $renewal_period) { // 删除旧Cookie,强制重新同意 setcookie( $this->cookie_name, '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true ); unset($_COOKIE[$this->cookie_name]); } } } } }
- <?php // includes/class-script-controller.php class ACCM_Script_Controller { private $consent_manager; private $blocked_scripts = array(); public function __construct() { $this->consent_manager = ACCM_Consent_Manager::get_instance(); // 注册脚本控制钩子 add_action('wp_head', array($this, 'add_script_control_scripts'), 1); add_filter('script_loader_tag', array($this, 'filter_script_tags'), 10, 3); add_action('wp_footer', array($this, 'load_blocked_scripts'), 99); } public function add_script_control_scripts() { // 添加脚本控制逻辑 ?> <script type="text/javascript"> window.accmScriptControl = { categories: <?php echo json_encode($this->consent_manager->get_cookie_categories()); ?>, hasConsent: function(category) { var consentData = this.getConsentData(); if (!consentData) return false; // 必要脚本始终允许 if (this.categories[category] && this.categories[category].required) { return true; } return consentData.categories && consentData.categories[category] === true; }, getConsentData: function() { try { var cookieValue = document.cookie .split('; ') .find(row => row.startsWith('accm_consent=')); if (cookieValue) { return JSON.parse(decodeURIComponent(cookieValue.split('=')[1])); } } catch(e) { console.error('Error parsing consent cookie:', e); } return null; }, loadScript: function(src, category, attributes) { if (!this.hasConsent(category)) { console.log('Script blocked due to missing consent:', src, 'Category:', category); return false; } var script = document.createElement('script'); script.src = src; if (attributes) { for (var attr in attributes) { if (attributes.hasOwnProperty(attr)) { script.setAttribute(attr, attributes[attr]); } } } document.head.appendChild(script); return true; } }; // 重写window.dataLayer.push以延迟Google Tag Manager if (typeof window.dataLayer === 'undefined') { window.dataLayer = []; } var originalDataLayerPush = window.dataLayer.push; window.dataLayer.push = function() { if (!accmScriptControl.hasConsent('analytics') && !accmScriptControl.hasConsent('marketing')) { console.log('GTM event blocked due to missing consent'); return; } return originalDataLayerPush.apply(this, arguments); }; </script> <?php } public function filter_script_tags($tag, $handle, $src) { // 获取脚本的Cookie类别 $script_categories = $this->get_script_categories($handle); if (empty($script_categories)) { return $tag; } // 检查是否所有需要的类别都有同意 $block_script = false; foreach ($script_categories as $category) { if (!$this->consent_manager->has_consent($category)) { $block_script = true; break; } } if ($block_script) { // 存储被阻止的脚本以便稍后加载 $this->blocked_scripts[] = array( 'tag' => $tag, 'handle' => $handle, 'src' => $src, 'categories' => $script_categories ); // 返回占位符或空字符串 return "<!-- Script '$handle' blocked due to missing cookie consent -->n"; } return $tag; } private function get_script_categories($handle) { $script_categories = array( 'google-analytics' => array('analytics'), 'gtm4wp' => array('analytics', 'marketing'), 'facebook-pixel' => array('marketing'), 'twitter-widgets' => array('marketing', 'preferences'), 'youtube-embed' => array('preferences'), 'vimeo-embed' => array('preferences'), 'google-maps' => array('preferences') ); // 允许通过过滤器添加或修改 $script_categories = apply_filters('accm_script_categories', $script_categories); return isset($script_categories[$handle]) ? $script_categories[$handle] : array(); } public function load_blocked_scripts() { if (empty($this->blocked_scripts)) { return; } ?> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { var blockedScripts = <?php echo json_encode($this->blocked_scripts); ?>; blockedScripts.forEach(function(scriptInfo) { var shouldLoad = true; scriptInfo.categories.forEach(function(category) { if (!accmScriptControl.hasConsent(category)) { shouldLoad = false; } }); if (shouldLoad) { // 创建并插入脚本 var script = document.createElement('script'); script.src = scriptInfo.src; // 复制原始属性 var regex = /(w+)=["']([^"']*)["']/g; var match; while ((match = regex.exec(scriptInfo.tag)) !== null) { if (match[1] !== 'src') { script.setAttribute(match[1], match[2]); } } document.head.appendChild(script); console.log('Previously blocked script loaded:', scriptInfo.handle); } }); }); </script> <?php } public function add_third_party_service($service_name, $script_code, $categories) { add_action('wp_footer', function() use ($service_name, $script_code, $categories) { $can_load = true; foreach ($categories as $category) { if (!$this->consent_manager->has_consent($category)) { $can_load = false; break; } } if ($can_load) { echo $script_code; } else { // 存储以便稍后加载 $this->blocked_scripts[] = array( 'tag' => $script_code, 'handle' => $service_name, 'categories' => $categories ); } }, 10); } }
- <?php // includes/class-settings-manager.php class ACCM_Settings_Manager { private $settings_page; private $settings_group = 'accm_settings_group'; private $settings_section = 'accm_settings_section'; private $option_name = 'accm_settings'; public function add_admin_menu() { $this->settings_page = add_options_page( __('Cookie同意设置', 'advanced-cookie-consent'), __('Cookie同意', 'advanced-cookie-consent'), 'manage_options', 'advanced-cookie-consent', array($this, 'render_settings_page') ); // 添加设置页面样式和脚本 add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets')); } public function enqueue_admin_assets($hook) { if ($hook !== $this->settings_page) { return; } wp_enqueue_style( 'accm-admin-style', ACCM_PLUGIN_URL . 'assets/css/admin.css', array(), ACCM_VERSION ); wp_enqueue_script( 'accm-admin-script', ACCM_PLUGIN_URL . 'assets/js/admin.js', array('jquery', 'wp-color-picker'), ACCM_VERSION, true ); // 启用颜色选择器 wp_enqueue_style('wp-color-picker'); } public function register_settings() { register_setting( $this->settings_group, $this->option_name, array($this, 'sanitize_settings') ); add_settings_section( $this->settings_section, __('基本设置', 'advanced-cookie-consent'), array($this, 'render_section_header'), 'advanced-cookie-consent' ); // 添加设置字段 $this->add_settings_fields(); } private function add_settings_fields() { $fields = array( array( 'id' => 'banner_title', 'title' => __('横幅标题', 'advanced-cookie-consent'), 'callback' => 'render_text_field', 'args' => array( 'description' => __('Cookie横幅的标题', 'advanced-cookie-consent'), 'default' => __('Cookie设置', 'advanced-cookie-consent') ) ), array( 'id' => 'banner_text', 'title' => __('横幅文本', 'advanced-cookie-consent'), 'callback' => 'render_textarea_field', 'args' => array( 'description' => __('Cookie横幅的主要说明文本', 'advanced-cookie-consent'), 'default' => __('我们使用Cookie来提升您的浏览体验,提供个性化内容并分析流量。点击"接受"即表示您同意我们使用所有Cookie。', 'advanced-cookie-consent'), 'rows' => 4 ) ), array( 'id' => 'banner_position', 'title' => __('横幅位置', 'advanced-cookie-consent'), 'callback' => 'render_select_field', 'args' => array( 'description' => __('选择Cookie横幅的显示位置', 'advanced-cookie-consent'), 'options' => array( 'bottom' => __('底部', 'advanced-cookie-consent'), 'top' => __('顶部', 'advanced-cookie-consent'), 'bottom-left' => __('左下角', 'advanced-cookie-consent'), 'bottom-right' => __('右下角', 'advanced-cookie-consent') ), 'default' => 'bottom' ) ), array( 'id' => 'banner_style', 'title' => __('横幅样式', 'advanced-cookie-consent'), 'callback' => 'render_select_field', 'args' => array( 'description' => __('选择Cookie横幅的视觉样式', 'advanced-cookie-consent'), 'options' => array( 'light' => __('浅色', 'advanced-cookie-consent'), 'dark' => __('深色', 'advanced-cookie-consent'), 'minimal' => __('极简', 'advanced-cookie-consent') ), 'default' => 'light' ) ), array( 'id' => 'primary_color', 'title' => __('主色调', 'advanced-cookie-consent'), 'callback' => 'render_color_field', 'args' => array(
-
在当今数字化时代,随着全球数据保护法规的不断完善,网站隐私合规性已成为每个网站所有者必须面对的重要课题。从欧盟的《通用数据保护条例》(GDPR)到加州的《消费者隐私法案》(CCPA),再到中国的《个人信息保护法》,全球各地都在加强对用户隐私的保护。对于使用WordPress构建的网站而言,如何有效管理Cookie和获取用户隐私同意,不仅是一项法律义务,更是建立用户信任的关键。
本教程将深入探讨如何通过WordPress代码二次开发,实现专业的Cookie合规性管理与用户隐私同意控件,同时集成常用互联网小工具功能。我们将从基础概念入手,逐步深入到具体实现,为您提供一套完整、实用的解决方案。
Cookie合规性指的是网站在使用Cookie和其他跟踪技术时,必须遵守相关隐私法规的要求。这主要包括:
- 知情同意原则:在设置非必要Cookie前,必须获得用户的明确同意
- 透明度原则:清晰告知用户网站使用了哪些Cookie及其目的
- 控制权原则:允许用户随时撤回同意或调整Cookie偏好
- 数据最小化原则:只收集实现特定目的所需的最少数据
- GDPR(欧盟通用数据保护条例):适用于处理欧盟公民数据的任何组织,无论其所在地
- CCPA(加州消费者隐私法案):保护加州居民的个人信息权利
- PIPL(中国个人信息保护法):规范在中国境内处理个人信息的活动
- ePrivacy指令:专门规范电子通信隐私,包括Cookie使用
WordPress作为内容管理系统,本身及其插件、主题都可能设置各种Cookie。常见的包括:
- 会话Cookie(用于用户登录状态)
- 评论功能Cookie
- 统计分析Cookie(如Google Analytics)
- 社交媒体集成Cookie
- 广告跟踪Cookie
一个完整的Cookie合规解决方案应包含以下核心功能:
- Cookie横幅/弹出窗口:首次访问时显示,请求用户同意
- Cookie偏好中心:允许用户详细管理各类Cookie
- 同意记录与证明:存储用户同意状态,以便审计
- 脚本加载控制:根据用户同意状态有条件加载第三方脚本
- 自动阻止功能:在获得同意前阻止非必要Cookie
- 定期重新同意:根据法规要求定期更新用户同意
我们将采用模块化设计,创建以下核心组件:
- 主控制器类:协调所有功能模块
- 前端展示模块:处理横幅和偏好中心的UI
- 同意管理模块:存储和管理用户同意状态
- 脚本控制模块:根据同意状态控制第三方脚本加载
- 设置管理模块:提供后台配置界面
- 小工具集成模块:扩展常用互联网工具功能
我们需要创建数据库表来存储:
- 用户同意记录
- Cookie分类和描述
- 第三方服务配置
- 同意历史记录
在开始编码前,请确保您已准备好:
- 本地WordPress开发环境:可以使用Local by Flywheel、XAMPP或Docker
- 代码编辑器:推荐VS Code、PHPStorm或Sublime Text
- 浏览器开发者工具:用于调试前端代码
- Git版本控制系统:管理代码变更
我们将创建一个独立的WordPress插件来实现所有功能:
<?php
/**
* Plugin Name: Advanced Cookie Consent Manager
* Plugin URI: https://yourwebsite.com/
* Description: 完整的Cookie合规性与隐私同意管理解决方案
* Version: 1.0.0
* Author: Your Name
* License: GPL v2 or later
* Text Domain: advanced-cookie-consent
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('ACCM_VERSION', '1.0.0');
define('ACCM_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('ACCM_PLUGIN_URL', plugin_dir_url(__FILE__));
define('ACCM_PLUGIN_BASENAME', plugin_basename(__FILE__));
创建以下目录结构:
advanced-cookie-consent/
├── includes/
│ ├── class-main-controller.php
│ ├── class-frontend-ui.php
│ ├── class-consent-manager.php
│ ├── class-script-controller.php
│ ├── class-settings-manager.php
│ └── class-widget-integration.php
├── assets/
│ ├── css/
│ │ ├── frontend.css
│ │ └── admin.css
│ ├── js/
│ │ ├── frontend.js
│ │ └── admin.js
│ └── images/
├── languages/
├── templates/
│ ├── cookie-banner.php
│ └── preference-center.php
└── advanced-cookie-consent.php
<?php
// includes/class-main-controller.php
class ACCM_Main_Controller {
private static $instance = null;
private $frontend_ui;
private $consent_manager;
private $script_controller;
private $settings_manager;
private $widget_integration;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
$this->load_dependencies();
$this->init_hooks();
}
private function load_dependencies() {
require_once ACCM_PLUGIN_DIR . 'includes/class-frontend-ui.php';
require_once ACCM_PLUGIN_DIR . 'includes/class-consent-manager.php';
require_once ACCM_PLUGIN_DIR . 'includes/class-script-controller.php';
require_once ACCM_PLUGIN_DIR . 'includes/class-settings-manager.php';
require_once ACCM_PLUGIN_DIR . 'includes/class-widget-integration.php';
$this->frontend_ui = new ACCM_Frontend_UI();
$this->consent_manager = new ACCM_Consent_Manager();
$this->script_controller = new ACCM_Script_Controller();
$this->settings_manager = new ACCM_Settings_Manager();
$this->widget_integration = new ACCM_Widget_Integration();
}
private function init_hooks() {
// 激活/停用插件钩子
register_activation_hook(__FILE__, array($this, 'activate_plugin'));
register_deactivation_hook(__FILE__, array($this, 'deactivate_plugin'));
// 初始化钩子
add_action('init', array($this, 'init'));
// 管理界面钩子
add_action('admin_menu', array($this->settings_manager, 'add_admin_menu'));
add_action('admin_init', array($this->settings_manager, 'register_settings'));
// 前端钩子
add_action('wp_enqueue_scripts', array($this->frontend_ui, 'enqueue_assets'));
add_action('wp_footer', array($this->frontend_ui, 'render_cookie_banner'));
// 脚本控制钩子
add_action('wp_head', array($this->script_controller, 'add_script_control_scripts'), 1);
}
public function init() {
// 加载文本域
load_plugin_textdomain('advanced-cookie-consent', false, dirname(ACCM_PLUGIN_BASENAME) . '/languages');
// 初始化组件
$this->consent_manager->init();
$this->widget_integration->init();
}
public function activate_plugin() {
// 创建数据库表
$this->consent_manager->create_tables();
// 设置默认选项
$this->settings_manager->set_default_options();
// 刷新重写规则
flush_rewrite_rules();
}
public function deactivate_plugin() {
// 清理临时数据
flush_rewrite_rules();
}
}
<?php
// includes/class-main-controller.php
class ACCM_Main_Controller {
private static $instance = null;
private $frontend_ui;
private $consent_manager;
private $script_controller;
private $settings_manager;
private $widget_integration;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
$this->load_dependencies();
$this->init_hooks();
}
private function load_dependencies() {
require_once ACCM_PLUGIN_DIR . 'includes/class-frontend-ui.php';
require_once ACCM_PLUGIN_DIR . 'includes/class-consent-manager.php';
require_once ACCM_PLUGIN_DIR . 'includes/class-script-controller.php';
require_once ACCM_PLUGIN_DIR . 'includes/class-settings-manager.php';
require_once ACCM_PLUGIN_DIR . 'includes/class-widget-integration.php';
$this->frontend_ui = new ACCM_Frontend_UI();
$this->consent_manager = new ACCM_Consent_Manager();
$this->script_controller = new ACCM_Script_Controller();
$this->settings_manager = new ACCM_Settings_Manager();
$this->widget_integration = new ACCM_Widget_Integration();
}
private function init_hooks() {
// 激活/停用插件钩子
register_activation_hook(__FILE__, array($this, 'activate_plugin'));
register_deactivation_hook(__FILE__, array($this, 'deactivate_plugin'));
// 初始化钩子
add_action('init', array($this, 'init'));
// 管理界面钩子
add_action('admin_menu', array($this->settings_manager, 'add_admin_menu'));
add_action('admin_init', array($this->settings_manager, 'register_settings'));
// 前端钩子
add_action('wp_enqueue_scripts', array($this->frontend_ui, 'enqueue_assets'));
add_action('wp_footer', array($this->frontend_ui, 'render_cookie_banner'));
// 脚本控制钩子
add_action('wp_head', array($this->script_controller, 'add_script_control_scripts'), 1);
}
public function init() {
// 加载文本域
load_plugin_textdomain('advanced-cookie-consent', false, dirname(ACCM_PLUGIN_BASENAME) . '/languages');
// 初始化组件
$this->consent_manager->init();
$this->widget_integration->init();
}
public function activate_plugin() {
// 创建数据库表
$this->consent_manager->create_tables();
// 设置默认选项
$this->settings_manager->set_default_options();
// 刷新重写规则
flush_rewrite_rules();
}
public function deactivate_plugin() {
// 清理临时数据
flush_rewrite_rules();
}
}
<?php
// includes/class-frontend-ui.php
class ACCM_Frontend_UI {
private $consent_manager;
public function __construct() {
$this->consent_manager = ACCM_Consent_Manager::get_instance();
}
public function enqueue_assets() {
// 前端样式
wp_enqueue_style(
'accm-frontend-style',
ACCM_PLUGIN_URL . 'assets/css/frontend.css',
array(),
ACCM_VERSION
);
// 前端脚本
wp_enqueue_script(
'accm-frontend-script',
ACCM_PLUGIN_URL . 'assets/js/frontend.js',
array('jquery'),
ACCM_VERSION,
true
);
// 本地化脚本
wp_localize_script('accm-frontend-script', 'accm_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('accm_nonce'),
'consent_categories' => $this->consent_manager->get_cookie_categories(),
'strings' => array(
'saving' => __('保存中...', 'advanced-cookie-consent'),
'saved' => __('设置已保存', 'advanced-cookie-consent'),
'error' => __('保存时出错,请重试', 'advanced-cookie-consent')
)
));
}
public function render_cookie_banner() {
// 检查是否已获得同意
if ($this->consent_manager->has_consent()) {
return;
}
// 获取设置
$settings = get_option('accm_settings', array());
// 包含横幅模板
include ACCM_PLUGIN_DIR . 'templates/cookie-banner.php';
}
public function render_preference_center() {
// 获取Cookie分类
$categories = $this->consent_manager->get_cookie_categories();
// 获取用户当前偏好
$user_preferences = $this->consent_manager->get_user_preferences();
// 包含偏好中心模板
include ACCM_PLUGIN_DIR . 'templates/preference-center.php';
}
}
<?php
// includes/class-frontend-ui.php
class ACCM_Frontend_UI {
private $consent_manager;
public function __construct() {
$this->consent_manager = ACCM_Consent_Manager::get_instance();
}
public function enqueue_assets() {
// 前端样式
wp_enqueue_style(
'accm-frontend-style',
ACCM_PLUGIN_URL . 'assets/css/frontend.css',
array(),
ACCM_VERSION
);
// 前端脚本
wp_enqueue_script(
'accm-frontend-script',
ACCM_PLUGIN_URL . 'assets/js/frontend.js',
array('jquery'),
ACCM_VERSION,
true
);
// 本地化脚本
wp_localize_script('accm-frontend-script', 'accm_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('accm_nonce'),
'consent_categories' => $this->consent_manager->get_cookie_categories(),
'strings' => array(
'saving' => __('保存中...', 'advanced-cookie-consent'),
'saved' => __('设置已保存', 'advanced-cookie-consent'),
'error' => __('保存时出错,请重试', 'advanced-cookie-consent')
)
));
}
public function render_cookie_banner() {
// 检查是否已获得同意
if ($this->consent_manager->has_consent()) {
return;
}
// 获取设置
$settings = get_option('accm_settings', array());
// 包含横幅模板
include ACCM_PLUGIN_DIR . 'templates/cookie-banner.php';
}
public function render_preference_center() {
// 获取Cookie分类
$categories = $this->consent_manager->get_cookie_categories();
// 获取用户当前偏好
$user_preferences = $this->consent_manager->get_user_preferences();
// 包含偏好中心模板
include ACCM_PLUGIN_DIR . 'templates/preference-center.php';
}
}
<?php
// templates/cookie-banner.php
$settings = get_option('accm_settings', array());
$banner_title = isset($settings['banner_title']) ? $settings['banner_title'] : __('Cookie设置', 'advanced-cookie-consent');
$banner_text = isset($settings['banner_text']) ? $settings['banner_text'] : __('我们使用Cookie来提升您的浏览体验,提供个性化内容并分析流量。点击"接受"即表示您同意我们使用所有Cookie。', 'advanced-cookie-consent');
$accept_text = isset($settings['accept_text']) ? $settings['accept_text'] : __('接受所有', 'advanced-cookie-consent');
$reject_text = isset($settings['reject_text']) ? $settings['reject_text'] : __('拒绝非必要', 'advanced-cookie-consent');
$preferences_text = isset($settings['preferences_text']) ? $settings['preferences_text'] : __('自定义设置', 'advanced-cookie-consent');
$privacy_policy_url = isset($settings['privacy_policy_url']) ? $settings['privacy_policy_url'] : get_privacy_policy_url();
$privacy_policy_text = isset($settings['privacy_policy_text']) ? $settings['privacy_policy_text'] : __('隐私政策', 'advanced-cookie-consent');
?>
<div id="accm-cookie-banner" class="accm-cookie-banner" style="display: none;">
<div class="accm-banner-content">
<div class="accm-banner-text">
<h3><?php echo esc_html($banner_title); ?></h3>
<p><?php echo esc_html($banner_text); ?></p>
<?php if ($privacy_policy_url): ?>
<p class="accm-privacy-link">
<a href="<?php echo esc_url($privacy_policy_url); ?>" target="_blank">
<?php echo esc_html($privacy_policy_text); ?>
</a>
</p>
<?php endif; ?>
</div>
<div class="accm-banner-buttons">
<button type="button" class="accm-btn accm-btn-preferences">
<?php echo esc_html($preferences_text); ?>
</button>
<button type="button" class="accm-btn accm-btn-reject">
<?php echo esc_html($reject_text); ?>
</button>
<button type="button" class="accm-btn accm-btn-accept accm-btn-primary">
<?php echo esc_html($accept_text); ?>
</button>
</div>
</div>
</div>
<div id="accm-preference-modal" class="accm-modal" style="display: none;">
<div class="accm-modal-content">
<div class="accm-modal-header">
<h3><?php _e('Cookie偏好设置', 'advanced-cookie-consent'); ?></h3>
<button type="button" class="accm-modal-close">×</button>
</div>
<div class="accm-modal-body">
<?php $this->render_preference_center(); ?>
</div>
<div class="accm-modal-footer">
<button type="button" class="accm-btn accm-btn-save-preferences accm-btn-primary">
<?php _e('保存设置', 'advanced-cookie-consent'); ?>
</button>
</div>
</div>
</div>
<?php
// templates/cookie-banner.php
$settings = get_option('accm_settings', array());
$banner_title = isset($settings['banner_title']) ? $settings['banner_title'] : __('Cookie设置', 'advanced-cookie-consent');
$banner_text = isset($settings['banner_text']) ? $settings['banner_text'] : __('我们使用Cookie来提升您的浏览体验,提供个性化内容并分析流量。点击"接受"即表示您同意我们使用所有Cookie。', 'advanced-cookie-consent');
$accept_text = isset($settings['accept_text']) ? $settings['accept_text'] : __('接受所有', 'advanced-cookie-consent');
$reject_text = isset($settings['reject_text']) ? $settings['reject_text'] : __('拒绝非必要', 'advanced-cookie-consent');
$preferences_text = isset($settings['preferences_text']) ? $settings['preferences_text'] : __('自定义设置', 'advanced-cookie-consent');
$privacy_policy_url = isset($settings['privacy_policy_url']) ? $settings['privacy_policy_url'] : get_privacy_policy_url();
$privacy_policy_text = isset($settings['privacy_policy_text']) ? $settings['privacy_policy_text'] : __('隐私政策', 'advanced-cookie-consent');
?>
<div id="accm-cookie-banner" class="accm-cookie-banner" style="display: none;">
<div class="accm-banner-content">
<div class="accm-banner-text">
<h3><?php echo esc_html($banner_title); ?></h3>
<p><?php echo esc_html($banner_text); ?></p>
<?php if ($privacy_policy_url): ?>
<p class="accm-privacy-link">
<a href="<?php echo esc_url($privacy_policy_url); ?>" target="_blank">
<?php echo esc_html($privacy_policy_text); ?>
</a>
</p>
<?php endif; ?>
</div>
<div class="accm-banner-buttons">
<button type="button" class="accm-btn accm-btn-preferences">
<?php echo esc_html($preferences_text); ?>
</button>
<button type="button" class="accm-btn accm-btn-reject">
<?php echo esc_html($reject_text); ?>
</button>
<button type="button" class="accm-btn accm-btn-accept accm-btn-primary">
<?php echo esc_html($accept_text); ?>
</button>
</div>
</div>
</div>
<div id="accm-preference-modal" class="accm-modal" style="display: none;">
<div class="accm-modal-content">
<div class="accm-modal-header">
<h3><?php _e('Cookie偏好设置', 'advanced-cookie-consent'); ?></h3>
<button type="button" class="accm-modal-close">×</button>
</div>
<div class="accm-modal-body">
<?php $this->render_preference_center(); ?>
</div>
<div class="accm-modal-footer">
<button type="button" class="accm-btn accm-btn-save-preferences accm-btn-primary">
<?php _e('保存设置', 'advanced-cookie-consent'); ?>
</button>
</div>
</div>
</div>
<?php
// includes/class-consent-manager.php
class ACCM_Consent_Manager {
private static $instance = null;
private $cookie_name = 'accm_consent';
private $cookie_expiry = 365; // 天数
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function init() {
// 处理AJAX请求
add_action('wp_ajax_accm_save_consent', array($this, 'ajax_save_consent'));
add_action('wp_ajax_nopriv_accm_save_consent', array($this, 'ajax_save_consent'));
// 检查并处理Cookie同意
$this->check_consent_cookie();
}
public function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'accm_consent_logs';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
consent_id varchar(32) NOT NULL,
user_id bigint(20) DEFAULT 0,
user_ip varchar(45) DEFAULT '',
user_agent text,
consent_data text NOT NULL,
consent_date datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY consent_id (consent_id),
KEY user_id (user_id),
KEY consent_date (consent_date)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
public function get_cookie_categories() {
$default_categories = array(
'necessary' => array(
'name' => __('必要', 'advanced-cookie-consent'),
'description' => __('这些Cookie对于网站的基本功能是必需的,无法关闭。', 'advanced-cookie-consent'),
'required' => true,
'default' => true
),
'preferences' => array(
'name' => __('偏好设置', 'advanced-cookie-consent'),
'description' => __('这些Cookie允许网站记住您的选择和偏好。', 'advanced-cookie-consent'),
'required' => false,
'default' => true
),
'analytics' => array(
'name' => __('统计分析', 'advanced-cookie-consent'),
'description' => __('这些Cookie帮助我们了解访问者如何与网站互动。', 'advanced-cookie-consent'),
'required' => false,
'default' => true
),
'marketing' => array(
'name' => __('营销', 'advanced-cookie-consent'),
'description' => __('这些Cookie用于跟踪广告效果和个性化广告。', 'advanced-cookie-consent'),
'required' => false,
'default' => false
)
);
// 允许通过过滤器添加或修改分类
return apply_filters('accm_cookie_categories', $default_categories);
}
public function has_consent($category = '') {
$consent_data = $this->get_consent_data();
if (empty($consent_data)) {
return false;
}
if (empty($category)) {
return !empty($consent_data);
}
$categories = $this->get_cookie_categories();
if (!isset($categories[$category])) {
return false;
}
// 必要Cookie始终视为已同意
<?php
// includes/class-consent-manager.php
class ACCM_Consent_Manager {
private static $instance = null;
private $cookie_name = 'accm_consent';
private $cookie_expiry = 365; // 天数
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function init() {
// 处理AJAX请求
add_action('wp_ajax_accm_save_consent', array($this, 'ajax_save_consent'));
add_action('wp_ajax_nopriv_accm_save_consent', array($this, 'ajax_save_consent'));
// 检查并处理Cookie同意
$this->check_consent_cookie();
}
public function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'accm_consent_logs';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
consent_id varchar(32) NOT NULL,
user_id bigint(20) DEFAULT 0,
user_ip varchar(45) DEFAULT '',
user_agent text,
consent_data text NOT NULL,
consent_date datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY consent_id (consent_id),
KEY user_id (user_id),
KEY consent_date (consent_date)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
public function get_cookie_categories() {
$default_categories = array(
'necessary' => array(
'name' => __('必要', 'advanced-cookie-consent'),
'description' => __('这些Cookie对于网站的基本功能是必需的,无法关闭。', 'advanced-cookie-consent'),
'required' => true,
'default' => true
),
'preferences' => array(
'name' => __('偏好设置', 'advanced-cookie-consent'),
'description' => __('这些Cookie允许网站记住您的选择和偏好。', 'advanced-cookie-consent'),
'required' => false,
'default' => true
),
'analytics' => array(
'name' => __('统计分析', 'advanced-cookie-consent'),
'description' => __('这些Cookie帮助我们了解访问者如何与网站互动。', 'advanced-cookie-consent'),
'required' => false,
'default' => true
),
'marketing' => array(
'name' => __('营销', 'advanced-cookie-consent'),
'description' => __('这些Cookie用于跟踪广告效果和个性化广告。', 'advanced-cookie-consent'),
'required' => false,
'default' => false
)
);
// 允许通过过滤器添加或修改分类
return apply_filters('accm_cookie_categories', $default_categories);
}
public function has_consent($category = '') {
$consent_data = $this->get_consent_data();
if (empty($consent_data)) {
return false;
}
if (empty($category)) {
return !empty($consent_data);
}
$categories = $this->get_cookie_categories();
if (!isset($categories[$category])) {
return false;
}
// 必要Cookie始终视为已同意
<?php
// includes/class-consent-manager.php(续)
if ($categories[$category]['required']) {
return true;
}
return isset($consent_data[$category]) && $consent_data[$category] === true;
}
private function get_consent_data() {
static $consent_data = null;
if ($consent_data !== null) {
return $consent_data;
}
// 首先检查Cookie
if (isset($_COOKIE[$this->cookie_name])) {
$cookie_data = json_decode(stripslashes($_COOKIE[$this->cookie_name]), true);
if (is_array($cookie_data)) {
$consent_data = $cookie_data;
return $consent_data;
}
}
// 如果没有Cookie,检查默认设置
$settings = get_option('accm_settings', array());
$default_consent = isset($settings['default_consent']) ? $settings['default_consent'] : 'none';
if ($default_consent === 'all') {
$categories = $this->get_cookie_categories();
$consent_data = array();
foreach ($categories as $key => $category) {
$consent_data[$key] = true;
}
} else {
$consent_data = array();
}
return $consent_data;
}
public function get_user_preferences() {
$consent_data = $this->get_consent_data();
$categories = $this->get_cookie_categories();
$preferences = array();
foreach ($categories as $key => $category) {
$preferences[$key] = array(
'name' => $category['name'],
'description' => $category['description'],
'required' => $category['required'],
'enabled' => $this->has_consent($key)
);
}
return $preferences;
}
public function ajax_save_consent() {
// 验证nonce
if (!check_ajax_referer('accm_nonce', 'nonce', false)) {
wp_die(json_encode(array(
'success' => false,
'message' => __('安全验证失败', 'advanced-cookie-consent')
)));
}
// 获取并验证数据
$consent_data = isset($_POST['consent_data']) ? $_POST['consent_data'] : array();
if (!is_array($consent_data)) {
wp_die(json_encode(array(
'success' => false,
'message' => __('无效的数据格式', 'advanced-cookie-consent')
)));
}
// 验证分类
$categories = $this->get_cookie_categories();
$validated_data = array();
foreach ($categories as $key => $category) {
if ($category['required']) {
$validated_data[$key] = true;
} else {
$validated_data[$key] = isset($consent_data[$key]) && $consent_data[$key] === 'true';
}
}
// 生成唯一ID
$consent_id = wp_generate_uuid4();
// 记录同意
$this->log_consent($consent_id, $validated_data);
// 设置Cookie
$this->set_consent_cookie($consent_id, $validated_data);
// 返回成功响应
wp_die(json_encode(array(
'success' => true,
'message' => __('设置已保存', 'advanced-cookie-consent'),
'consent_id' => $consent_id
)));
}
private function log_consent($consent_id, $consent_data) {
global $wpdb;
$table_name = $wpdb->prefix . 'accm_consent_logs';
$user_id = get_current_user_id();
$user_ip = $this->get_user_ip();
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$wpdb->insert(
$table_name,
array(
'consent_id' => $consent_id,
'user_id' => $user_id,
'user_ip' => $user_ip,
'user_agent' => $user_agent,
'consent_data' => json_encode($consent_data)
),
array('%s', '%d', '%s', '%s', '%s')
);
}
private function set_consent_cookie($consent_id, $consent_data) {
$cookie_data = array(
'consent_id' => $consent_id,
'categories' => $consent_data,
'timestamp' => time()
);
$cookie_value = json_encode($cookie_data);
// 设置Cookie
setcookie(
$this->cookie_name,
$cookie_value,
time() + ($this->cookie_expiry * DAY_IN_SECONDS),
COOKIEPATH,
COOKIE_DOMAIN,
is_ssl(),
true // HttpOnly
);
// 立即在本次请求中可用
$_COOKIE[$this->cookie_name] = $cookie_value;
}
private function get_user_ip() {
$ip = '';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '';
}
private function check_consent_cookie() {
// 检查Cookie是否需要更新
if (isset($_COOKIE[$this->cookie_name])) {
$cookie_data = json_decode(stripslashes($_COOKIE[$this->cookie_name]), true);
if (is_array($cookie_data) && isset($cookie_data['timestamp'])) {
$cookie_age = time() - $cookie_data['timestamp'];
$renewal_period = 365 * DAY_IN_SECONDS; // 一年后重新请求同意
if ($cookie_age > $renewal_period) {
// 删除旧Cookie,强制重新同意
setcookie(
$this->cookie_name,
'',
time() - 3600,
COOKIEPATH,
COOKIE_DOMAIN,
is_ssl(),
true
);
unset($_COOKIE[$this->cookie_name]);
}
}
}
}
}
<?php
// includes/class-consent-manager.php(续)
if ($categories[$category]['required']) {
return true;
}
return isset($consent_data[$category]) && $consent_data[$category] === true;
}
private function get_consent_data() {
static $consent_data = null;
if ($consent_data !== null) {
return $consent_data;
}
// 首先检查Cookie
if (isset($_COOKIE[$this->cookie_name])) {
$cookie_data = json_decode(stripslashes($_COOKIE[$this->cookie_name]), true);
if (is_array($cookie_data)) {
$consent_data = $cookie_data;
return $consent_data;
}
}
// 如果没有Cookie,检查默认设置
$settings = get_option('accm_settings', array());
$default_consent = isset($settings['default_consent']) ? $settings['default_consent'] : 'none';
if ($default_consent === 'all') {
$categories = $this->get_cookie_categories();
$consent_data = array();
foreach ($categories as $key => $category) {
$consent_data[$key] = true;
}
} else {
$consent_data = array();
}
return $consent_data;
}
public function get_user_preferences() {
$consent_data = $this->get_consent_data();
$categories = $this->get_cookie_categories();
$preferences = array();
foreach ($categories as $key => $category) {
$preferences[$key] = array(
'name' => $category['name'],
'description' => $category['description'],
'required' => $category['required'],
'enabled' => $this->has_consent($key)
);
}
return $preferences;
}
public function ajax_save_consent() {
// 验证nonce
if (!check_ajax_referer('accm_nonce', 'nonce', false)) {
wp_die(json_encode(array(
'success' => false,
'message' => __('安全验证失败', 'advanced-cookie-consent')
)));
}
// 获取并验证数据
$consent_data = isset($_POST['consent_data']) ? $_POST['consent_data'] : array();
if (!is_array($consent_data)) {
wp_die(json_encode(array(
'success' => false,
'message' => __('无效的数据格式', 'advanced-cookie-consent')
)));
}
// 验证分类
$categories = $this->get_cookie_categories();
$validated_data = array();
foreach ($categories as $key => $category) {
if ($category['required']) {
$validated_data[$key] = true;
} else {
$validated_data[$key] = isset($consent_data[$key]) && $consent_data[$key] === 'true';
}
}
// 生成唯一ID
$consent_id = wp_generate_uuid4();
// 记录同意
$this->log_consent($consent_id, $validated_data);
// 设置Cookie
$this->set_consent_cookie($consent_id, $validated_data);
// 返回成功响应
wp_die(json_encode(array(
'success' => true,
'message' => __('设置已保存', 'advanced-cookie-consent'),
'consent_id' => $consent_id
)));
}
private function log_consent($consent_id, $consent_data) {
global $wpdb;
$table_name = $wpdb->prefix . 'accm_consent_logs';
$user_id = get_current_user_id();
$user_ip = $this->get_user_ip();
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$wpdb->insert(
$table_name,
array(
'consent_id' => $consent_id,
'user_id' => $user_id,
'user_ip' => $user_ip,
'user_agent' => $user_agent,
'consent_data' => json_encode($consent_data)
),
array('%s', '%d', '%s', '%s', '%s')
);
}
private function set_consent_cookie($consent_id, $consent_data) {
$cookie_data = array(
'consent_id' => $consent_id,
'categories' => $consent_data,
'timestamp' => time()
);
$cookie_value = json_encode($cookie_data);
// 设置Cookie
setcookie(
$this->cookie_name,
$cookie_value,
time() + ($this->cookie_expiry * DAY_IN_SECONDS),
COOKIEPATH,
COOKIE_DOMAIN,
is_ssl(),
true // HttpOnly
);
// 立即在本次请求中可用
$_COOKIE[$this->cookie_name] = $cookie_value;
}
private function get_user_ip() {
$ip = '';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '';
}
private function check_consent_cookie() {
// 检查Cookie是否需要更新
if (isset($_COOKIE[$this->cookie_name])) {
$cookie_data = json_decode(stripslashes($_COOKIE[$this->cookie_name]), true);
if (is_array($cookie_data) && isset($cookie_data['timestamp'])) {
$cookie_age = time() - $cookie_data['timestamp'];
$renewal_period = 365 * DAY_IN_SECONDS; // 一年后重新请求同意
if ($cookie_age > $renewal_period) {
// 删除旧Cookie,强制重新同意
setcookie(
$this->cookie_name,
'',
time() - 3600,
COOKIEPATH,
COOKIE_DOMAIN,
is_ssl(),
true
);
unset($_COOKIE[$this->cookie_name]);
}
}
}
}
}
<?php
// includes/class-script-controller.php
class ACCM_Script_Controller {
private $consent_manager;
private $blocked_scripts = array();
public function __construct() {
$this->consent_manager = ACCM_Consent_Manager::get_instance();
// 注册脚本控制钩子
add_action('wp_head', array($this, 'add_script_control_scripts'), 1);
add_filter('script_loader_tag', array($this, 'filter_script_tags'), 10, 3);
add_action('wp_footer', array($this, 'load_blocked_scripts'), 99);
}
public function add_script_control_scripts() {
// 添加脚本控制逻辑
?>
<script type="text/javascript">
window.accmScriptControl = {
categories: <?php echo json_encode($this->consent_manager->get_cookie_categories()); ?>,
hasConsent: function(category) {
var consentData = this.getConsentData();
if (!consentData) return false;
// 必要脚本始终允许
if (this.categories[category] && this.categories[category].required) {
return true;
}
return consentData.categories && consentData.categories[category] === true;
},
getConsentData: function() {
try {
var cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('accm_consent='));
if (cookieValue) {
return JSON.parse(decodeURIComponent(cookieValue.split('=')[1]));
}
} catch(e) {
console.error('Error parsing consent cookie:', e);
}
return null;
},
loadScript: function(src, category, attributes) {
if (!this.hasConsent(category)) {
console.log('Script blocked due to missing consent:', src, 'Category:', category);
return false;
}
var script = document.createElement('script');
script.src = src;
if (attributes) {
for (var attr in attributes) {
if (attributes.hasOwnProperty(attr)) {
script.setAttribute(attr, attributes[attr]);
}
}
}
document.head.appendChild(script);
return true;
}
};
// 重写window.dataLayer.push以延迟Google Tag Manager
if (typeof window.dataLayer === 'undefined') {
window.dataLayer = [];
}
var originalDataLayerPush = window.dataLayer.push;
window.dataLayer.push = function() {
if (!accmScriptControl.hasConsent('analytics') && !accmScriptControl.hasConsent('marketing')) {
console.log('GTM event blocked due to missing consent');
return;
}
return originalDataLayerPush.apply(this, arguments);
};
</script>
<?php
}
public function filter_script_tags($tag, $handle, $src) {
// 获取脚本的Cookie类别
$script_categories = $this->get_script_categories($handle);
if (empty($script_categories)) {
return $tag;
}
// 检查是否所有需要的类别都有同意
$block_script = false;
foreach ($script_categories as $category) {
if (!$this->consent_manager->has_consent($category)) {
$block_script = true;
break;
}
}
if ($block_script) {
// 存储被阻止的脚本以便稍后加载
$this->blocked_scripts[] = array(
'tag' => $tag,
'handle' => $handle,
'src' => $src,
'categories' => $script_categories
);
// 返回占位符或空字符串
return "<!-- Script '$handle' blocked due to missing cookie consent -->n";
}
return $tag;
}
private function get_script_categories($handle) {
$script_categories = array(
'google-analytics' => array('analytics'),
'gtm4wp' => array('analytics', 'marketing'),
'facebook-pixel' => array('marketing'),
'twitter-widgets' => array('marketing', 'preferences'),
'youtube-embed' => array('preferences'),
'vimeo-embed' => array('preferences'),
'google-maps' => array('preferences')
);
// 允许通过过滤器添加或修改
$script_categories = apply_filters('accm_script_categories', $script_categories);
return isset($script_categories[$handle]) ? $script_categories[$handle] : array();
}
public function load_blocked_scripts() {
if (empty($this->blocked_scripts)) {
return;
}
?>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var blockedScripts = <?php echo json_encode($this->blocked_scripts); ?>;
blockedScripts.forEach(function(scriptInfo) {
var shouldLoad = true;
scriptInfo.categories.forEach(function(category) {
if (!accmScriptControl.hasConsent(category)) {
shouldLoad = false;
}
});
if (shouldLoad) {
// 创建并插入脚本
var script = document.createElement('script');
script.src = scriptInfo.src;
// 复制原始属性
var regex = /(w+)=["']([^"']*)["']/g;
var match;
while ((match = regex.exec(scriptInfo.tag)) !== null) {
if (match[1] !== 'src') {
script.setAttribute(match[1], match[2]);
}
}
document.head.appendChild(script);
console.log('Previously blocked script loaded:', scriptInfo.handle);
}
});
});
</script>
<?php
}
public function add_third_party_service($service_name, $script_code, $categories) {
add_action('wp_footer', function() use ($service_name, $script_code, $categories) {
$can_load = true;
foreach ($categories as $category) {
if (!$this->consent_manager->has_consent($category)) {
$can_load = false;
break;
}
}
if ($can_load) {
echo $script_code;
} else {
// 存储以便稍后加载
$this->blocked_scripts[] = array(
'tag' => $script_code,
'handle' => $service_name,
'categories' => $categories
);
}
}, 10);
}
}
<?php
// includes/class-script-controller.php
class ACCM_Script_Controller {
private $consent_manager;
private $blocked_scripts = array();
public function __construct() {
$this->consent_manager = ACCM_Consent_Manager::get_instance();
// 注册脚本控制钩子
add_action('wp_head', array($this, 'add_script_control_scripts'), 1);
add_filter('script_loader_tag', array($this, 'filter_script_tags'), 10, 3);
add_action('wp_footer', array($this, 'load_blocked_scripts'), 99);
}
public function add_script_control_scripts() {
// 添加脚本控制逻辑
?>
<script type="text/javascript">
window.accmScriptControl = {
categories: <?php echo json_encode($this->consent_manager->get_cookie_categories()); ?>,
hasConsent: function(category) {
var consentData = this.getConsentData();
if (!consentData) return false;
// 必要脚本始终允许
if (this.categories[category] && this.categories[category].required) {
return true;
}
return consentData.categories && consentData.categories[category] === true;
},
getConsentData: function() {
try {
var cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('accm_consent='));
if (cookieValue) {
return JSON.parse(decodeURIComponent(cookieValue.split('=')[1]));
}
} catch(e) {
console.error('Error parsing consent cookie:', e);
}
return null;
},
loadScript: function(src, category, attributes) {
if (!this.hasConsent(category)) {
console.log('Script blocked due to missing consent:', src, 'Category:', category);
return false;
}
var script = document.createElement('script');
script.src = src;
if (attributes) {
for (var attr in attributes) {
if (attributes.hasOwnProperty(attr)) {
script.setAttribute(attr, attributes[attr]);
}
}
}
document.head.appendChild(script);
return true;
}
};
// 重写window.dataLayer.push以延迟Google Tag Manager
if (typeof window.dataLayer === 'undefined') {
window.dataLayer = [];
}
var originalDataLayerPush = window.dataLayer.push;
window.dataLayer.push = function() {
if (!accmScriptControl.hasConsent('analytics') && !accmScriptControl.hasConsent('marketing')) {
console.log('GTM event blocked due to missing consent');
return;
}
return originalDataLayerPush.apply(this, arguments);
};
</script>
<?php
}
public function filter_script_tags($tag, $handle, $src) {
// 获取脚本的Cookie类别
$script_categories = $this->get_script_categories($handle);
if (empty($script_categories)) {
return $tag;
}
// 检查是否所有需要的类别都有同意
$block_script = false;
foreach ($script_categories as $category) {
if (!$this->consent_manager->has_consent($category)) {
$block_script = true;
break;
}
}
if ($block_script) {
// 存储被阻止的脚本以便稍后加载
$this->blocked_scripts[] = array(
'tag' => $tag,
'handle' => $handle,
'src' => $src,
'categories' => $script_categories
);
// 返回占位符或空字符串
return "<!-- Script '$handle' blocked due to missing cookie consent -->n";
}
return $tag;
}
private function get_script_categories($handle) {
$script_categories = array(
'google-analytics' => array('analytics'),
'gtm4wp' => array('analytics', 'marketing'),
'facebook-pixel' => array('marketing'),
'twitter-widgets' => array('marketing', 'preferences'),
'youtube-embed' => array('preferences'),
'vimeo-embed' => array('preferences'),
'google-maps' => array('preferences')
);
// 允许通过过滤器添加或修改
$script_categories = apply_filters('accm_script_categories', $script_categories);
return isset($script_categories[$handle]) ? $script_categories[$handle] : array();
}
public function load_blocked_scripts() {
if (empty($this->blocked_scripts)) {
return;
}
?>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var blockedScripts = <?php echo json_encode($this->blocked_scripts); ?>;
blockedScripts.forEach(function(scriptInfo) {
var shouldLoad = true;
scriptInfo.categories.forEach(function(category) {
if (!accmScriptControl.hasConsent(category)) {
shouldLoad = false;
}
});
if (shouldLoad) {
// 创建并插入脚本
var script = document.createElement('script');
script.src = scriptInfo.src;
// 复制原始属性
var regex = /(w+)=["']([^"']*)["']/g;
var match;
while ((match = regex.exec(scriptInfo.tag)) !== null) {
if (match[1] !== 'src') {
script.setAttribute(match[1], match[2]);
}
}
document.head.appendChild(script);
console.log('Previously blocked script loaded:', scriptInfo.handle);
}
});
});
</script>
<?php
}
public function add_third_party_service($service_name, $script_code, $categories) {
add_action('wp_footer', function() use ($service_name, $script_code, $categories) {
$can_load = true;
foreach ($categories as $category) {
if (!$this->consent_manager->has_consent($category)) {
$can_load = false;
break;
}
}
if ($can_load) {
echo $script_code;
} else {
// 存储以便稍后加载
$this->blocked_scripts[] = array(
'tag' => $script_code,
'handle' => $service_name,
'categories' => $categories
);
}
}, 10);
}
}
<?php
// includes/class-settings-manager.php
class ACCM_Settings_Manager {
private $settings_page;
private $settings_group = 'accm_settings_group';
private $settings_section = 'accm_settings_section';
private $option_name = 'accm_settings';
public function add_admin_menu() {
$this->settings_page = add_options_page(
__('Cookie同意设置', 'advanced-cookie-consent'),
__('Cookie同意', 'advanced-cookie-consent'),
'manage_options',
'advanced-cookie-consent',
array($this, 'render_settings_page')
);
// 添加设置页面样式和脚本
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
}
public function enqueue_admin_assets($hook) {
if ($hook !== $this->settings_page) {
return;
}
wp_enqueue_style(
'accm-admin-style',
ACCM_PLUGIN_URL . 'assets/css/admin.css',
array(),
ACCM_VERSION
);
wp_enqueue_script(
'accm-admin-script',
ACCM_PLUGIN_URL . 'assets/js/admin.js',
array('jquery', 'wp-color-picker'),
ACCM_VERSION,
true
);
// 启用颜色选择器
wp_enqueue_style('wp-color-picker');
}
public function register_settings() {
register_setting(
$this->settings_group,
$this->option_name,
array($this, 'sanitize_settings')
);
add_settings_section(
$this->settings_section,
__('基本设置', 'advanced-cookie-consent'),
array($this, 'render_section_header'),
'advanced-cookie-consent'
);
// 添加设置字段
$this->add_settings_fields();
}
private function add_settings_fields() {
$fields = array(
array(
'id' => 'banner_title',
'title' => __('横幅标题', 'advanced-cookie-consent'),
'callback' => 'render_text_field',
'args' => array(
'description' => __('Cookie横幅的标题', 'advanced-cookie-consent'),
'default' => __('Cookie设置', 'advanced-cookie-consent')
)
),
array(
'id' => 'banner_text',
'title' => __('横幅文本', 'advanced-cookie-consent'),
'callback' => 'render_textarea_field',
'args' => array(
'description' => __('Cookie横幅的主要说明文本', 'advanced-cookie-consent'),
'default' => __('我们使用Cookie来提升您的浏览体验,提供个性化内容并分析流量。点击"接受"即表示您同意我们使用所有Cookie。', 'advanced-cookie-consent'),
'rows' => 4
)
),
array(
'id' => 'banner_position',
'title' => __('横幅位置', 'advanced-cookie-consent'),
'callback' => 'render_select_field',
'args' => array(
'description' => __('选择Cookie横幅的显示位置', 'advanced-cookie-consent'),
'options' => array(
'bottom' => __('底部', 'advanced-cookie-consent'),
'top' => __('顶部', 'advanced-cookie-consent'),
'bottom-left' => __('左下角', 'advanced-cookie-consent'),
'bottom-right' => __('右下角', 'advanced-cookie-consent')
),
'default' => 'bottom'
)
),
array(
'id' => 'banner_style',
'title' => __('横幅样式', 'advanced-cookie-consent'),
'callback' => 'render_select_field',
'args' => array(
'description' => __('选择Cookie横幅的视觉样式', 'advanced-cookie-consent'),
'options' => array(
'light' => __('浅色', 'advanced-cookie-consent'),
'dark' => __('深色', 'advanced-cookie-consent'),
'minimal' => __('极简', 'advanced-cookie-consent')
),
'default' => 'light'
)
),
array(
'id' => 'primary_color',
'title' => __('主色调', 'advanced-cookie-consent'),
'callback' => 'render_color_field',
'args' => array(
<?php
// includes/class-settings-manager.php
class ACCM_Settings_Manager {
private $settings_page;
private $settings_group = 'accm_settings_group';
private $settings_section = 'accm_settings_section';
private $option_name = 'accm_settings';
public function add_admin_menu() {
$this->settings_page = add_options_page(
__('Cookie同意设置', 'advanced-cookie-consent'),
__('Cookie同意', 'advanced-cookie-consent'),
'manage_options',
'advanced-cookie-consent',
array($this, 'render_settings_page')
);
// 添加设置页面样式和脚本
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
}
public function enqueue_admin_assets($hook) {
if ($hook !== $this->settings_page) {
return;
}
wp_enqueue_style(
'accm-admin-style',
ACCM_PLUGIN_URL . 'assets/css/admin.css',
array(),
ACCM_VERSION
);
wp_enqueue_script(
'accm-admin-script',
ACCM_PLUGIN_URL . 'assets/js/admin.js',
array('jquery', 'wp-color-picker'),
ACCM_VERSION,
true
);
// 启用颜色选择器
wp_enqueue_style('wp-color-picker');
}
public function register_settings() {
register_setting(
$this->settings_group,
$this->option_name,
array($this, 'sanitize_settings')
);
add_settings_section(
$this->settings_section,
__('基本设置', 'advanced-cookie-consent'),
array($this, 'render_section_header'),
'advanced-cookie-consent'
);
// 添加设置字段
$this->add_settings_fields();
}
private function add_settings_fields() {
$fields = array(
array(
'id' => 'banner_title',
'title' => __('横幅标题', 'advanced-cookie-consent'),
'callback' => 'render_text_field',
'args' => array(
'description' => __('Cookie横幅的标题', 'advanced-cookie-consent'),
'default' => __('Cookie设置', 'advanced-cookie-consent')
)
),
array(
'id' => 'banner_text',
'title' => __('横幅文本', 'advanced-cookie-consent'),
'callback' => 'render_textarea_field',
'args' => array(
'description' => __('Cookie横幅的主要说明文本', 'advanced-cookie-consent'),
'default' => __('我们使用Cookie来提升您的浏览体验,提供个性化内容并分析流量。点击"接受"即表示您同意我们使用所有Cookie。', 'advanced-cookie-consent'),
'rows' => 4
)
),
array(
'id' => 'banner_position',
'title' => __('横幅位置', 'advanced-cookie-consent'),
'callback' => 'render_select_field',
'args' => array(
'description' => __('选择Cookie横幅的显示位置', 'advanced-cookie-consent'),
'options' => array(
'bottom' => __('底部', 'advanced-cookie-consent'),
'top' => __('顶部', 'advanced-cookie-consent'),
'bottom-left' => __('左下角', 'advanced-cookie-consent'),
'bottom-right' => __('右下角', 'advanced-cookie-consent')
),
'default' => 'bottom'
)
),
array(
'id' => 'banner_style',
'title' => __('横幅样式', 'advanced-cookie-consent'),
'callback' => 'render_select_field',
'args' => array(
'description' => __('选择Cookie横幅的视觉样式', 'advanced-cookie-consent'),
'options' => array(
'light' => __('浅色', 'advanced-cookie-consent'),
'dark' => __('深色', 'advanced-cookie-consent'),
'minimal' => __('极简', 'advanced-cookie-consent')
),
'default' => 'light'
)
),
array(
'id' => 'primary_color',
'title' => __('主色调', 'advanced-cookie-consent'),
'callback' => 'render_color_field',
'args' => array(


