首页 / 应用软件 / 手把手教程,在WordPress中集成网站Cookie合规管理与用户同意横幅

手把手教程,在WordPress中集成网站Cookie合规管理与用户同意横幅

手把手教程:在WordPress中集成网站Cookie合规管理与用户同意横幅,通过WordPress程序的代码二次开发实现常用互联网小工具功能

引言:为什么Cookie合规管理如此重要?

在当今数字时代,数据隐私已成为全球关注的焦点。随着欧盟《通用数据保护条例》(GDPR)、加州消费者隐私法案(CCPA)以及中国《个人信息保护法》等法规的实施,网站所有者必须确保其在线平台符合数据保护要求。Cookie作为网站跟踪用户行为、存储偏好设置的关键工具,其使用必须透明且获得用户明确同意。

WordPress作为全球最流行的内容管理系统,驱动着超过40%的网站。然而,许多WordPress网站所有者并未充分意识到Cookie合规的重要性,或不知道如何正确实施合规解决方案。本教程将手把手指导您通过代码二次开发,在WordPress中集成完整的Cookie合规管理系统,包括用户同意横幅、偏好设置中心和常用互联网小工具功能。

第一部分:理解Cookie合规的基本要求

1.1 主要数据保护法规概述

在开始技术实施之前,了解相关法规的基本要求至关重要:

  • GDPR(欧盟通用数据保护条例):要求网站在使用非必要Cookie前获得用户明确、知情的同意
  • CCPA(加州消费者隐私法案):赋予加州居民了解其个人信息被收集、拒绝出售个人信息的权利
  • ePrivacy指令:专门规范电子通信隐私,包括Cookie使用
  • 中国《个人信息保护法》:规定个人信息处理应取得个人同意,并遵循最小必要原则

1.2 Cookie分类与合规要求

根据功能,Cookie通常分为以下几类:

  1. 必要Cookie:确保网站基本功能运行,无需用户同意
  2. 偏好Cookie:记住用户选择(如语言、地区),需要用户同意
  3. 统计Cookie:收集匿名数据用于分析,需要用户同意
  4. 营销Cookie:跟踪用户行为用于广告定向,需要明确同意

1.3 WordPress网站Cookie合规现状

大多数WordPress网站通过以下方式使用Cookie:

  • 核心WordPress:使用登录认证Cookie
  • 主题和插件:添加各种功能性和跟踪Cookie
  • 第三方服务:如Google Analytics、Facebook像素等

第二部分:规划Cookie合规解决方案架构

2.1 系统需求分析

一个完整的Cookie合规管理系统应包含:

  1. 可定制的同意横幅:清晰说明Cookie使用目的
  2. 同意管理平台:允许用户查看和修改偏好设置
  3. Cookie分类拦截:在获得同意前阻止非必要脚本
  4. 同意记录:存储用户同意状态和偏好
  5. 定期重新同意:根据法规要求定期更新同意

2.2 技术架构设计

我们将构建一个轻量级但功能完整的解决方案:

  • 前端组件:使用HTML、CSS和JavaScript创建响应式横幅和设置面板
  • 后端处理:使用PHP处理同意状态存储和脚本管理
  • 数据库设计:存储用户同意偏好和日志
  • 集成机制:与WordPress核心和第三方插件无缝集成

第三部分:创建WordPress插件基础结构

3.1 初始化插件文件

首先,在wp-content/plugins目录下创建新文件夹"cookie-compliance-manager",然后创建主插件文件:

<?php
/**
 * Plugin Name: Cookie Compliance Manager
 * Plugin URI: https://yourwebsite.com/
 * Description: 完整的Cookie合规管理与用户同意解决方案
 * Version: 1.0.0
 * Author: Your Name
 * License: GPL v2 or later
 * Text Domain: cookie-compliance-manager
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('CCM_VERSION', '1.0.0');
define('CCM_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CCM_PLUGIN_URL', plugin_dir_url(__FILE__));

// 初始化插件
require_once CCM_PLUGIN_DIR . 'includes/class-cookie-compliance-manager.php';

function run_cookie_compliance_manager() {
    $plugin = new Cookie_Compliance_Manager();
    $plugin->run();
}
run_cookie_compliance_manager();

3.2 创建主管理类

在includes目录下创建主类文件:

<?php
class Cookie_Compliance_Manager {
    
    private $loader;
    
    public function __construct() {
        $this->load_dependencies();
        $this->define_admin_hooks();
        $this->define_public_hooks();
    }
    
    private function load_dependencies() {
        require_once CCM_PLUGIN_DIR . 'includes/class-ccm-loader.php';
        require_once CCM_PLUGIN_DIR . 'includes/class-ccm-i18n.php';
        require_once CCM_PLUGIN_DIR . 'admin/class-ccm-admin.php';
        require_once CCM_PLUGIN_DIR . 'public/class-ccm-public.php';
        
        $this->loader = new CCM_Loader();
    }
    
    private function define_admin_hooks() {
        $plugin_admin = new CCM_Admin();
        
        $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles');
        $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts');
        $this->loader->add_action('admin_menu', $plugin_admin, 'add_admin_menu');
        $this->loader->add_action('admin_init', $plugin_admin, 'register_settings');
    }
    
    private function define_public_hooks() {
        $plugin_public = new CCM_Public();
        
        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_styles');
        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_scripts');
        $this->loader->add_action('wp_head', $plugin_public, 'insert_cookie_consent_banner');
        $this->loader->add_action('wp_footer', $plugin_public, 'insert_cookie_settings_modal');
        $this->loader->add_action('init', $plugin_public, 'handle_ajax_requests');
    }
    
    public function run() {
        $this->loader->run();
    }
}

第四部分:构建Cookie同意横幅前端界面

4.1 设计响应式Cookie横幅

创建public/css/ccm-public.css文件:

/* Cookie同意横幅基础样式 */
.ccm-cookie-banner {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #2c3e50;
    color: #ecf0f1;
    padding: 20px;
    z-index: 999999;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
    display: none;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
}

.ccm-banner-content {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
}

.ccm-banner-text {
    flex: 1;
    min-width: 300px;
    margin-right: 20px;
}

.ccm-banner-text h3 {
    margin: 0 0 10px 0;
    color: #3498db;
    font-size: 1.2em;
}

.ccm-banner-text p {
    margin: 0 0 15px 0;
    line-height: 1.5;
    font-size: 14px;
}

.ccm-banner-text a {
    color: #3498db;
    text-decoration: underline;
}

.ccm-banner-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.ccm-btn {
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: 600;
    transition: all 0.3s ease;
    font-size: 14px;
}

.ccm-btn-accept-all {
    background: #27ae60;
    color: white;
}

.ccm-btn-accept-all:hover {
    background: #219653;
}

.ccm-btn-settings {
    background: #3498db;
    color: white;
}

.ccm-btn-settings:hover {
    background: #2980b9;
}

.ccm-btn-reject-all {
    background: #e74c3c;
    color: white;
}

.ccm-btn-reject-all:hover {
    background: #c0392b;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .ccm-banner-content {
        flex-direction: column;
        text-align: center;
    }
    
    .ccm-banner-text {
        margin-right: 0;
        margin-bottom: 15px;
    }
    
    .ccm-banner-actions {
        justify-content: center;
    }
}

4.2 创建Cookie设置模态窗口

添加设置面板的HTML结构和CSS:

/* Cookie设置模态窗口 */
.ccm-settings-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.8);
    z-index: 1000000;
    overflow-y: auto;
}

.ccm-modal-content {
    background: white;
    margin: 50px auto;
    max-width: 800px;
    border-radius: 8px;
    box-shadow: 0 5px 30px rgba(0,0,0,0.3);
    color: #333;
}

.ccm-modal-header {
    padding: 20px 30px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.ccm-modal-header h2 {
    margin: 0;
    color: #2c3e50;
}

.ccm-close-modal {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #7f8c8d;
}

.ccm-modal-body {
    padding: 30px;
}

.ccm-cookie-category {
    margin-bottom: 25px;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 6px;
    background: #f9f9f9;
}

.ccm-category-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.ccm-category-header h3 {
    margin: 0;
    color: #2c3e50;
}

.ccm-category-toggle {
    position: relative;
    display: inline-block;
    width: 50px;
    height: 24px;
}

.ccm-category-toggle input {
    opacity: 0;
    width: 0;
    height: 0;
}

.ccm-toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: .4s;
    border-radius: 24px;
}

.ccm-toggle-slider:before {
    position: absolute;
    content: "";
    height: 16px;
    width: 16px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    transition: .4s;
    border-radius: 50%;
}

input:checked + .ccm-toggle-slider {
    background-color: #27ae60;
}

input:checked + .ccm-toggle-slider:before {
    transform: translateX(26px);
}

.ccm-category-description {
    color: #666;
    font-size: 14px;
    line-height: 1.5;
}

.ccm-cookie-list {
    margin-top: 15px;
    font-size: 13px;
}

.ccm-cookie-item {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid #eee;
}

.ccm-modal-footer {
    padding: 20px 30px;
    border-top: 1px solid #eee;
    text-align: right;
    background: #f9f9f9;
    border-radius: 0 0 8px 8px;
}

第五部分:实现JavaScript交互功能

5.1 创建主JavaScript文件

在public/js/ccm-public.js中实现核心交互逻辑:

(function($) {
    'use strict';
    
    var CCM = {
        // 初始化
        init: function() {
            this.bindEvents();
            this.checkConsent();
            this.loadBlockedScripts();
        },
        
        // 绑定事件
        bindEvents: function() {
            // 接受所有Cookie
            $(document).on('click', '.ccm-btn-accept-all', function(e) {
                e.preventDefault();
                CCM.saveConsent('all');
                CCM.hideBanner();
            });
            
            // 拒绝所有非必要Cookie
            $(document).on('click', '.ccm-btn-reject-all', function(e) {
                e.preventDefault();
                CCM.saveConsent('necessary');
                CCM.hideBanner();
            });
            
            // 打开设置
            $(document).on('click', '.ccm-btn-settings', function(e) {
                e.preventDefault();
                CCM.showSettingsModal();
            });
            
            // 关闭模态窗口
            $(document).on('click', '.ccm-close-modal', function() {
                CCM.hideSettingsModal();
            });
            
            // 保存设置
            $(document).on('click', '.ccm-save-settings', function() {
                CCM.saveCustomConsent();
            });
            
            // 阻止模态窗口外部点击关闭
            $(document).on('click', '.ccm-settings-modal', function(e) {
                if ($(e.target).hasClass('ccm-settings-modal')) {
                    CCM.hideSettingsModal();
                }
            });
        },
        
        // 显示Cookie横幅
        showBanner: function() {
            $('.ccm-cookie-banner').fadeIn(300);
            $('body').addClass('ccm-banner-visible');
        },
        
        // 隐藏Cookie横幅
        hideBanner: function() {
            $('.ccm-cookie-banner').fadeOut(300);
            $('body').removeClass('ccm-banner-visible');
        },
        
        // 显示设置模态窗口
        showSettingsModal: function() {
            $('.ccm-settings-modal').fadeIn(300);
            $('body').addClass('ccm-modal-visible');
            this.hideBanner();
        },
        
        // 隐藏设置模态窗口
        hideSettingsModal: function() {
            $('.ccm-settings-modal').fadeOut(300);
            $('body').removeClass('ccm-modal-visible');
        },
        
        // 检查同意状态
        checkConsent: function() {
            var consent = this.getConsent();
            
            if (!consent || consent.status === 'pending') {
                this.showBanner();
            } else {
                this.hideBanner();
            }
        },
        
        // 获取同意状态
        getConsent: function() {
            var consentCookie = this.getCookie('ccm_consent');
            
            if (consentCookie) {
                try {
                    return JSON.parse(decodeURIComponent(consentCookie));
                } catch (e) {
                    return null;
                }
            }
            
            return null;
        },
        
        // 保存同意设置
        saveConsent: function(type) {
            var consent = {
                version: '1.0',
                date: new Date().toISOString(),
                status: 'given'
            };
            
            switch(type) {
                case 'all':
                    consent.categories = {
                        necessary: true,
                        preferences: true,
                        statistics: true,
                        marketing: true
                    };
                    break;
                    
                case 'necessary':
                    consent.categories = {
                        necessary: true,
                        preferences: false,
                        statistics: false,
                        marketing: false
                    };
                    break;
                    
                default:
                    // 自定义设置
                    consent.categories = this.getCategorySelections();
            }
            
            // 设置Cookie(365天过期)
            this.setCookie('ccm_consent', JSON.stringify(consent), 365);
            
            // 触发同意更改事件
            $(document).trigger('ccm_consent_changed', [consent]);
            
            // 重新加载被阻止的脚本
            this.loadBlockedScripts();
        },
        
        // 保存自定义同意设置
        saveCustomConsent: function() {
            this.saveConsent('custom');
            this.hideSettingsModal();
            this.showNotification('设置已保存成功!');
        },
        
        // 获取类别选择
        getCategorySelections: function() {
            return {
                necessary: true, // 必要Cookie始终启用
                preferences: $('#ccm-category-preferences').is(':checked'),
                statistics: $('#ccm-category-statistics').is(':checked'),
                marketing: $('#ccm-category-marketing').is(':checked')
            };
        },
        
        // 加载被阻止的脚本
        loadBlockedScripts: function() {
            var consent = this.getConsent();
            
            if (!consent || !consent.categories) {
                return;
            }
            
            // 根据同意类别加载脚本
            if (consent.categories.statistics) {
                this.loadStatisticsScripts();
            }
            
            if (consent.categories.marketing) {
                this.loadMarketingScripts();
            }
        },
        
        // 加载统计脚本
        loadStatisticsScripts: function() {
            // 加载Google Analytics
            if (window.ccmConfig.gaTrackingId) {
                this.loadGoogleAnalytics(window.ccmConfig.gaTrackingId);
            }
            
            // 这里可以添加其他统计脚本
        },
        
        // 加载Google Analytics
        loadGoogleAnalytics: function(trackingId) {
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}

gtag('config', trackingId, { 'anonymize_ip': true });

        
        var script = document.createElement('script');
        script.async = true;
        script.src = 'https://www.googletagmanager.com/gtag/js?id=' + trackingId;
        document.head.appendChild(script);
    },
    
    // 加载营销脚本
    loadMarketingScripts: function() {
        // 加载Facebook像素
        if (window.ccmConfig.fbPixelId) {
            this.loadFacebookPixel(window.ccmConfig.fbPixelId);
        }
        
        // 这里可以添加其他营销脚本
    },
    
    // 加载Facebook像素
    loadFacebookPixel: function(pixelId) {
        !function(f,b,e,v,n,t,s)
        {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
        n.callMethod.apply(n,arguments):n.queue.push(arguments)};
        if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
        n.queue=[];t=b.createElement(e);t.async=!0;
        t.src=v;s=b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t,s)}(window, document,'script',
        'https://connect.facebook.net/en_US/fbevents.js');
        fbq('init', pixelId);
        fbq('track', 'PageView');
    },
    
    // Cookie操作辅助函数
    setCookie: function(name, value, days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/; SameSite=Lax";
    },
    
    getCookie: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    },
    
    // 显示通知
    showNotification: function(message) {
        var notification = $('<div class="ccm-notification">' + message + '</div>');
        $('body').append(notification);
        
        notification.css({
            position: 'fixed',
            top: '20px',
            right: '20px',
            background: '#27ae60',
            color: 'white',
            padding: '15px 20px',
            borderRadius: '4px',
            zIndex: '1000001',
            boxShadow: '0 2px 10px rgba(0,0,0,0.2)'
        });
        
        setTimeout(function() {
            notification.fadeOut(300, function() {
                $(this).remove();
            });
        }, 3000);
    }
};

// 文档加载完成后初始化
$(document).ready(function() {
    CCM.init();
});

// 暴露到全局作用域
window.CookieComplianceManager = CCM;

})(jQuery);


### 第六部分:实现PHP后端处理逻辑

#### 6.1 创建公共功能类

在public/class-ccm-public.php中实现后端逻辑:

<?php
class CCM_Public {


private $plugin_name;
private $version;

public function __construct() {
    $this->plugin_name = 'cookie-compliance-manager';
    $this->version = CCM_VERSION;
}

// 注册前端样式和脚本
public function enqueue_styles() {
    wp_enqueue_style(
        $this->plugin_name,
        CCM_PLUGIN_URL . 'public/css/ccm-public.css',
        array(),
        $this->version,
        'all'
    );
}

public function enqueue_scripts() {
    wp_enqueue_script(
        'jquery'
    );
    
    wp_enqueue_script(
        $this->plugin_name,
        CCM_PLUGIN_URL . 'public/js/ccm-public.js',
        array('jquery'),
        $this->version,
        true
    );
    
    // 传递配置到JavaScript
    wp_localize_script($this->plugin_name, 'ccmConfig', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'gaTrackingId' => get_option('ccm_ga_tracking_id', ''),
        'fbPixelId' => get_option('ccm_fb_pixel_id', ''),
        'nonce' => wp_create_nonce('ccm_nonce')
    ));
}

// 插入Cookie同意横幅
public function insert_cookie_consent_banner() {
    if ($this->should_show_banner()) {
        ?>
        <div class="ccm-cookie-banner" id="ccm-cookie-banner">
            <div class="ccm-banner-content">
                <div class="ccm-banner-text">
                    <h3>Cookie设置</h3>
                    <p>我们使用Cookie来提升您的浏览体验、分析网站流量并个性化内容。点击"接受所有"即表示您同意我们使用所有Cookie。您可以通过"Cookie设置"管理您的偏好。了解更多,请查看我们的<a href="<?php echo get_privacy_policy_url(); ?>">隐私政策</a>。</p>
                </div>
                <div class="ccm-banner-actions">
                    <button type="button" class="ccm-btn ccm-btn-accept-all">接受所有</button>
                    <button type="button" class="ccm-btn ccm-btn-settings">Cookie设置</button>
                    <button type="button" class="ccm-btn ccm-btn-reject-all">拒绝非必要</button>
                </div>
            </div>
        </div>
        <?php
    }
}

// 插入Cookie设置模态窗口
public function insert_cookie_settings_modal() {
    ?>
    <div class="ccm-settings-modal" id="ccm-settings-modal">
        <div class="ccm-modal-content">
            <div class="ccm-modal-header">
                <h2>Cookie偏好设置</h2>
                <button type="button" class="ccm-close-modal">&times;</button>
            </div>
            <div class="ccm-modal-body">
                <p>您可以选择接受或拒绝不同类型的Cookie。必要Cookie对于网站基本功能是必需的,无法被拒绝。</p>
                
                <div class="ccm-cookie-category">
                    <div class="ccm-category-header">
                        <h3>必要Cookie</h3>
                        <label class="ccm-category-toggle">
                            <input type="checkbox" id="ccm-category-necessary" checked disabled>
                            <span class="ccm-toggle-slider"></span>
                        </label>
                    </div>
                    <div class="ccm-category-description">
                        <p>这些Cookie对于网站的基本功能是必需的,无法被禁用。它们通常仅针对您所做的操作(例如设置隐私偏好、登录或填写表单)而设置。</p>
                    </div>
                </div>
                
                <div class="ccm-cookie-category">
                    <div class="ccm-category-header">
                        <h3>偏好Cookie</h3>
                        <label class="ccm-category-toggle">
                            <input type="checkbox" id="ccm-category-preferences">
                            <span class="ccm-toggle-slider"></span>
                        </label>
                    </div>
                    <div class="ccm-category-description">
                        <p>这些Cookie使网站能够记住您所做的选择(例如用户名、语言或地区),并提供增强的个性化功能。</p>
                    </div>
                </div>
                
                <div class="ccm-cookie-category">
                    <div class="ccm-category-header">
                        <h3>统计Cookie</h3>
                        <label class="ccm-category-toggle">
                            <input type="checkbox" id="ccm-category-statistics">
                            <span class="ccm-toggle-slider"></span>
                        </label>
                    </div>
                    <div class="ccm-category-description">
                        <p>这些Cookie帮助我们了解访问者如何与网站互动,收集匿名信息用于改进网站功能。</p>
                        <div class="ccm-cookie-list">
                            <div class="ccm-cookie-item">
                                <span>Google Analytics</span>
                                <span>分析用户行为</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="ccm-cookie-category">
                    <div class="ccm-category-header">
                        <h3>营销Cookie</h3>
                        <label class="ccm-category-toggle">
                            <input type="checkbox" id="ccm-category-marketing">
                            <span class="ccm-toggle-slider"></span>
                        </label>
                    </div>
                    <div class="ccm-category-description">
                        <p>这些Cookie用于跟踪访问者跨网站的浏览习惯,以显示更相关的广告。</p>
                        <div class="ccm-cookie-list">
                            <div class="ccm-cookie-item">
                                <span>Facebook Pixel</span>
                                <span>广告效果跟踪</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="ccm-modal-footer">
                <button type="button" class="ccm-btn ccm-btn-accept-all">接受所有</button>
                <button type="button" class="ccm-btn ccm-btn-save-settings">保存设置</button>
                <button type="button" class="ccm-btn ccm-btn-reject-all">仅接受必要</button>
            </div>
        </div>
    </div>
    <?php
}

// 处理AJAX请求
public function handle_ajax_requests() {
    add_action('wp_ajax_ccm_save_consent', array($this, 'ajax_save_consent'));
    add_action('wp_ajax_nopriv_ccm_save_consent', array($this, 'ajax_save_consent'));
    
    add_action('wp_ajax_ccm_get_consent', array($this, 'ajax_get_consent'));
    add_action('wp_ajax_nopriv_ccm_get_consent', array($this, 'ajax_get_consent'));
}

// AJAX保存同意设置
public function ajax_save_consent() {
    check_ajax_referer('ccm_nonce', 'nonce');
    
    $consent_data = array(
        'version' => '1.0',
        'date' => current_time('mysql'),
        'ip_address' => $this->get_user_ip(),
        'user_agent' => $_SERVER['HTTP_USER_AGENT'],
        'categories' => array(
            'necessary' => true,
            'preferences' => isset($_POST['preferences']) ? filter_var($_POST['preferences'], FILTER_VALIDATE_BOOLEAN) : false,
            'statistics' => isset($_POST['statistics']) ? filter_var($_POST['statistics'], FILTER_VALIDATE_BOOLEAN) : false,
            'marketing' => isset($_POST['marketing']) ? filter_var($_POST['marketing'], FILTER_VALIDATE_BOOLEAN) : false
        )
    );
    
    // 保存到数据库
    $this->save_consent_to_db($consent_data);
    
    // 设置Cookie
    $this->set_consent_cookie($consent_data);
    
    wp_send_json_success(array(
        'message' => '同意设置已保存',
        'consent' => $consent_data
    ));
}

// AJAX获取同意设置
public function ajax_get_consent() {
    $consent = $this->get_user_consent();
    
    if ($consent) {
        wp_send_json_success($consent);
    } else {
        wp_send_json_error('未找到同意记录');
    }
}

// 保存同意到数据库
private function save_consent_to_db($consent_data) {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'ccm_consents';
    
    $data = array(
        'user_id' => get_current_user_id(),
        'ip_address' => $consent_data['ip_address'],
        'user_agent' => $consent_data['user_agent'],
        'consent_data' => json_encode($consent_data),
        'created_at' => current_time('mysql')
    );
    
    $wpdb->insert($table_name, $data);
}

// 设置同意Cookie
private function set_consent_cookie($consent_data) {
    $cookie_value = json_encode($consent_data);
    $expiry = time() + (365 * 24 * 60 * 60); // 1年
    
    setcookie('ccm_consent', $cookie_value, $expiry, '/', '', is_ssl(), true);
}

// 获取用户同意状态
private function get_user_consent() {
    if (isset($_COOKIE['ccm_consent'])) {
        return json_decode(stripslashes($_COOKIE['ccm_consent']), true);
    }
    
    return null;
}

// 检查是否应该显示横幅
private function should_show_banner() {
    // 如果用户已经做出选择,不显示横幅
    $consent = $this->get_user_consent();
    if ($consent && isset($consent['date'])) {
        return false;
    }
    
    // 检查是否在管理页面
    if (is_admin()) {
        return false;
    }
    
    // 检查是否在特定页面排除
    $excluded_pages = get_option('ccm_excluded_pages', array());
    if (is_page($excluded_pages)) {
        return false;
    }
    
    return true;
}

// 获取用户IP地址
private function get_user_ip() {
    $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
    
    foreach ($ip_keys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                    return $ip;
                }
            }
        }
    }
    
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

}


### 第七部分:创建管理后台界面

#### 7.1 构建管理设置页面

在admin/class-ccm-admin.php中创建管理界面:

<?php
class CCM_Admin {


private $plugin_name;
private $version;

public function __construct() {
    $this->plugin_name = 'cookie-compliance-manager';
    $this->version = CCM_VERSION;
}

// 注册管理菜单
public function add_admin_menu() {
    add_menu_page(
        'Cookie合规管理',
        'Cookie合规',
        'manage_options',
        'cookie-compliance-manager',
        array($this, 'display_admin_page'),
        'dashicons-shield',
        80
    );
    
    add_submenu_page(
        'cookie-compliance-manager',
        '设置',
        '设置',
        'manage_options',
        'cookie-compliance-settings',
        array($this, 'display_settings_page')
    );
    
    add_submenu_page(
        'cookie-compliance-manager',
        '同意记录',
        '同意记录',
        'manage_options',
        'cookie-compliance-consents',
        array($this, 'display_consents_page')
    );
}

// 显示主管理页面
public function display_admin_page() {
    ?>
    <div class="wrap">
        <h1>Cookie合规管理</h1>
        
        <div class="ccm-admin-container">
            <div class="ccm-admin-header">
                <div class="ccm-stats-cards">
                    <div class="ccm-stat-card">
                        <h3>总同意数</h3>
                        <p class="ccm-stat-number"><?php echo $this->get_total_consents(); ?></p>
                    </div>
                    <div class="ccm-stat-card">
                        <h3>今日同意</h3>
                        <p class="ccm-stat-number"><?php echo $this->get_today_consents(); ?></p>
                    </div>
                    <div class="ccm-stat-card">
                        <h3>接受率</h3>
                        <p class="ccm-stat-number"><?php echo $this->get_acceptance_rate(); ?>%</p>
                    </div>
                </div>
            </div>
            
            <div class="ccm-admin-content">
                <div class="ccm-welcome-panel">
                    <h2>欢迎使用Cookie合规管理器</h2>
                    <p>确保您的网站符合GDPR、CCPA等数据保护法规要求。</p>
                    
                    <div class="ccm-quick-links">
                        <a href="?page=cookie-compliance-settings" class="button button-primary">配置设置</a>
                        <a href="?page=cookie-compliance-consents" class="button">查看同意记录</a>
                        <a href="#" class="button">生成隐私政策</a>
                    </div>
                </div>
                
                <div class="ccm-compliance-status">
                    <h3>合规状态检查</h3>
                    <ul class="ccm-status-list">
                        <li class="ccm-status-item <?php echo $this->check_banner_status() ? 'ccm-status-ok' : 'ccm-status-error'; ?>">
                            <span
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5226.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

工作时间:周一至周五,9:00-17:30,节假日休息
返回顶部