文章目录
- 在当今数字化营销时代,网络传媒广告的精准投放对于企业营销效果至关重要。WordPress作为全球最流行的内容管理系统,为广告投放提供了强大的平台支持。本文将详细介绍如何配置一款柔性广告投放WordPress插件,帮助您实现智能化、个性化的广告管理。
-
- 激活插件后,您会在WordPress侧边栏看到"广告管理"菜单。首次使用时,需要进行基础配置: /** * 广告插件基础配置示例代码 * 这段代码展示了如何初始化广告插件的基本设置 */ // 定义广告系统常量 define('AD_SYSTEM_VERSION', '2.1.0'); define('AD_MAX_IMPRESSIONS', 10000); // 默认最大展示次数 define('AD_CLICK_LIMIT', 500); // 默认点击限制 class AdConfigInitializer { /** * 初始化广告插件配置 * @param array $options 配置选项数组 * @return bool 初始化是否成功 */ public static function initialize($options = array()) { // 默认配置 $defaults = array( 'enable_rotation' => true, // 启用广告轮播 'geo_targeting' => false, // 地理定位 'device_targeting' => true, // 设备定向 'time_targeting' => false, // 时间定向 'frequency_capping' => true, // 频次控制 'impressions_per_day' => 1000, // 每日展示上限 'default_ad_size' => '728x90', // 默认广告尺寸 'enable_analytics' => true // 启用分析功能 ); // 合并用户配置与默认配置 $config = wp_parse_args($options, $defaults); // 保存配置到数据库 $result = update_option('flexible_ad_config', $config); // 创建必要的数据库表 self::create_database_tables(); return $result; } /** * 创建广告系统所需的数据库表 */ private static function create_database_tables() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); // 广告活动表 $campaigns_table = $wpdb->prefix . 'ad_campaigns'; $campaigns_sql = "CREATE TABLE IF NOT EXISTS $campaigns_table ( id mediumint(9) NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, start_date datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, end_date datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, budget decimal(10,2) DEFAULT 0.00, status varchar(20) DEFAULT 'active', targeting_rules text, PRIMARY KEY (id) ) $charset_collate;"; // 广告单元表 $ad_units_table = $wpdb->prefix . 'ad_units'; $ad_units_sql = "CREATE TABLE IF NOT EXISTS $ad_units_table ( id mediumint(9) NOT NULL AUTO_INCREMENT, campaign_id mediumint(9) NOT NULL, title varchar(255) NOT NULL, ad_type varchar(50) NOT NULL, content text NOT NULL, display_rules text, impressions int DEFAULT 0, clicks int DEFAULT 0, weight int DEFAULT 1, PRIMARY KEY (id), KEY campaign_id (campaign_id) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($campaigns_sql); dbDelta($ad_units_sql); } } // 初始化配置示例 $initial_options = array( 'enable_rotation' => true, 'geo_targeting' => true, // 启用地理定位 'impressions_per_day' => 5000 ); AdConfigInitializer::initialize($initial_options);
- 在"广告管理"→"广告位"中,您可以创建和管理不同的广告位: 点击"添加新广告位" 输入广告位名称(如:首页横幅、文章内嵌等) 设置广告位尺寸和类型 配置展示规则(特定页面、分类等) 保存设置
-
- 地理定位允许您根据访客的地理位置展示不同的广告内容: /** * 地理定位广告示例 * 根据用户地理位置显示特定广告 */ class GeoTargetingAd { /** * 根据地理位置获取适合的广告 * @param string $location 用户地理位置 * @param array $available_ads 可用广告数组 * @return array 匹配的广告 */ public static function get_geo_targeted_ad($location, $available_ads) { // 地理位置映射规则 $geo_rules = array( '北京' => array('ad_1', 'ad_2', 'ad_3'), '上海' => array('ad_4', 'ad_5'), '广州' => array('ad_6', 'ad_7', 'ad_8'), '深圳' => array('ad_9', 'ad_10'), 'default' => array('ad_default') // 默认广告 ); // 检查是否有特定地区的广告 if (isset($geo_rules[$location])) { $targeted_ad_ids = $geo_rules[$location]; } else { $targeted_ad_ids = $geo_rules['default']; } // 过滤出符合条件的广告 $filtered_ads = array(); foreach ($available_ads as $ad) { if (in_array($ad['id'], $targeted_ad_ids)) { $filtered_ads[] = $ad; } } // 如果没有找到特定广告,返回默认广告 if (empty($filtered_ads)) { foreach ($available_ads as $ad) { if (in_array($ad['id'], $geo_rules['default'])) { $filtered_ads[] = $ad; } } } return $filtered_ads; } /** * 获取用户地理位置(简化示例) * 实际应用中可能需要使用IP定位服务 * @return string 地理位置 */ public static function detect_user_location() { // 这里可以使用第三方IP定位API // 简化示例:从cookie或session中获取 if (isset($_COOKIE['user_location'])) { return sanitize_text_field($_COOKIE['user_location']); } // 默认位置 return 'default'; } } // 使用示例 $user_location = GeoTargetingAd::detect_user_location(); $available_ads = array( array('id' => 'ad_1', 'content' => '北京地区专属广告'), array('id' => 'ad_4', 'content' => '上海地区专属广告'), array('id' => 'ad_default', 'content' => '默认广告内容') ); $targeted_ads = GeoTargetingAd::get_geo_targeted_ad($user_location, $available_ads);
- 行为定向基于用户的历史行为展示相关广告: 进入"广告管理"→"行为定向" 创建行为规则(如:浏览过产品页的用户) 设置触发条件和展示广告 配置重定向频率和持续时间
-
- 广告轮播确保多个广告公平展示: /** * 智能广告轮播系统 * 支持权重控制和频次限制 */ class AdRotator { /** * 根据权重选择广告 * @param array $ads 广告数组,包含权重信息 * @return array 选中的广告 */ public static function select_ad_by_weight($ads) { if (empty($ads)) { return null; } // 计算总权重 $total_weight = 0; foreach ($ads as $ad) { $total_weight += isset($ad['weight']) ? $ad['weight'] : 1; } // 生成随机数 $random = mt_rand(1, $total_weight); // 根据权重选择广告 $current_weight = 0; foreach ($ads as $ad) { $ad_weight = isset($ad['weight']) ? $ad['weight'] : 1; $current_weight += $ad_weight; if ($random <= $current_weight) { return $ad; } } // 如果未选中,返回第一个广告 return $ads[0]; } /** * 频次控制:检查广告是否可展示 * @param string $ad_id 广告ID * @param string $user_id 用户标识 * @param int $max_impressions 最大展示次数 * @return bool 是否可以展示 */ public static function check_frequency($ad_id, $user_id, $max_impressions = 3) { // 获取用户广告展示记录 $user_ad_key = 'user_ad_impressions_' . $user_id; $impressions = get_transient($user_ad_key); if (!$impressions) { $impressions = array(); } // 检查该广告的展示次数 $ad_impressions = isset($impressions[$ad_id]) ? $impressions[$ad_id] : 0; // 如果超过限制,返回false if ($ad_impressions >= $max_impressions) { return false; } // 更新展示次数 $impressions[$ad_id] = $ad_impressions + 1; set_transient($user_ad_key, $impressions, DAY_IN_SECONDS); // 24小时有效 return true; } } // 使用示例 $ads = array( array('id' => 'ad_1', 'content' => '广告1', 'weight' => 3), array('id' => 'ad_2', 'content' => '广告2', 'weight' => 2), array('id' => 'ad_3', 'content' => '广告3', 'weight' => 1) ); // 选择广告 $selected_ad = AdRotator::select_ad_by_weight($ads); // 检查频次 $user_id = get_current_user_id() ?: $_SERVER['REMOTE_ADDR']; if (AdRotator::check_frequency($selected_ad['id'], $user_id, 5)) { // 展示广告 echo $selected_ad['content']; }
- 进入"广告管理"→"频次控制" 设置每个用户每天看到同一广告的最大次数 配置时间窗口(小时、天、周) 设置例外规则(如VIP用户不受限制)
-
- 插件内置数据分析功能,您也可以集成第三方分析工具: /** * 广告效果跟踪器 * 记录展示、点击和转化数据 */ class AdPerformanceTracker { /** * 记录广告展示 * @param string $ad_id 广告ID * @param string $page_url 页面URL * @param string $user_agent 用户代理 */ public static function track_impression($ad_id, $page_url = '', $user_agent = '') { global $wpdb; $table_name = $wpdb->prefix . 'ad_statistics'; $data = array( 'ad_id' => $ad_id, 'event_type' => 'impression', 'page_url' => $page_url ?: $_SERVER['REQUEST_URI'], 'user_agent' => $user_agent ?: $_SERVER['HTTP_USER_AGENT'], 'ip_address' => $_SERVER['REMOTE_ADDR'], 'created_at' => current_time('mysql') ); $wpdb->insert($table_name, $data); // 更新广告单元的总展示数 self::update_ad_unit_stats($ad_id, 'impressions'); } /** * 记录广告点击 * @param string $ad_id 广告ID * @param string $referrer 来源页面 */ public static function track_click($ad_id, $referrer = '') { global $wpdb; $table_name = $wpdb->prefix . 'ad_statistics'; $data = array( 'ad_id' => $ad_id, 'event_type' => 'click', 'page_url' => $referrer ?: $_SERVER['HTTP_REFERER'], 'ip_address' => $_SERVER['REMOTE_ADDR'], 'created_at' => current_time('mysql') ); $wpdb->insert($table_name, $data); // 更新广告单元的总点击数 self::update_ad_unit_stats($ad_id, 'clicks'); } /** * 更新广告单元统计 * @param string $ad_id 广告ID * @param string $field 要更新的字段 */ private static function update_ad_unit_stats($ad_id, $field) { global $wpdb; $table_name = $wpdb->prefix . 'ad_units'; $wpdb->query( $wpdb->prepare( "UPDATE $table_name SET $field = $field + 1 WHERE id = %d", $ad_id ) ); } /** * 获取广告效果报告 * @param string $ad_id 广告ID * @param string $start_date 开始日期 * @param string $end_date 结束日期 * @return array 统计数据 */ public static function get_performance_report($ad_id = '', $start_date = '', $end_date = '') { global $wpdb; $table_name = $wpdb->prefix . 'ad_statistics'; $where_clause = '1=1'; $prepare_args = array(); if ($ad_id) { $where_clause .= ' AND ad_id = %s'; $prepare_args[] = $ad_id; } if ($start_date) { $where_clause .= ' AND created_at >= %s'; $prepare_args[] = $start_date; } if ($end_date) { $where_clause .= ' AND created_at <= %s'; $prepare_args[] = $end_date; } $query = "SELECT ad_id, SUM(CASE WHEN event_type = 'impression' THEN 1 ELSE 0 END) as impressions, SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) as clicks, COUNT(DISTINCT ip_address) as unique_visitors FROM $table_name WHERE $where_clause GROUP BY ad_id"; if (!empty($prepare_args)) { $query = $wpdb->prepare($query, $prepare_args); } $results = $wpdb->get_results($query, ARRAY_A); // 计算点击率 foreach ($results as &$row) { if ($row['impressions'] > 0) { $row['ctr'] = round(($row['clicks'] / $row['impressions']) * 100, 2); } else { $row['ctr'] = 0; } } return $results; } } // 使用示例:在广告展示时调用 AdPerformanceTracker::track_impression('ad_123', 'https://example.com/page'); // 在广告点击时调用(通常通过AJAX) add_action('wp_ajax_track_ad_click', function() { $ad_id = isset($_POST['ad_id']) ? sanitize_text_field($_POST['ad_id']) : ''; if ($ad_id) { AdPerformanceTracker::track_click($ad_id); wp_die('success'); } });
- 创建广告变体(不同标题、图片或呼吁用语) 设置测试参数(样本大小、测试时长) 定义成功指标(点击率、转化率) 启动测试并监控结果
- 通过合理配置柔性广告投放WordPress插件,您可以实现高度定制化的广告展示策略,提升广告效果
-
-
- 动态内容匹配技术能够分析页面内容并展示相关广告,大幅提升广告相关性和点击率: /** * 内容智能匹配广告系统 * 分析页面内容关键词并匹配相关广告 */ class ContentAwareAdMatcher { /** * 提取页面关键词 * @param int $post_id 文章ID * @return array 关键词数组 */ public static function extract_keywords($post_id) { $post = get_post($post_id); if (!$post) { return array(); } // 获取文章内容 $content = $post->post_content . ' ' . $post->post_title; // 移除HTML标签和短代码 $content = wp_strip_all_tags($content); $content = strip_shortcodes($content); // 分词处理(简化版,实际可使用NLP库) $words = str_word_count($content, 1); // 移除停用词 $stop_words = array('的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'); $words = array_diff($words, $stop_words); // 统计词频 $word_freq = array_count_values($words); // 按频率排序并取前10个关键词 arsort($word_freq); $keywords = array_slice(array_keys($word_freq), 0, 10); return $keywords; } /** * 匹配相关广告 * @param array $keywords 关键词数组 * @param array $ads 广告数组 * @return array 匹配的广告 */ public static function match_ads_by_keywords($keywords, $ads) { $matched_ads = array(); foreach ($ads as $ad) { $score = 0; // 检查广告关键词匹配 if (isset($ad['keywords'])) { $ad_keywords = is_array($ad['keywords']) ? $ad['keywords'] : explode(',', $ad['keywords']); foreach ($keywords as $keyword) { foreach ($ad_keywords as $ad_keyword) { // 使用相似度算法(简化版) similar_text(strtolower($keyword), strtolower($ad_keyword), $percent); if ($percent > 80) { // 相似度超过80% $score += $percent / 100; } } } } // 检查广告分类匹配 if (isset($ad['categories'])) { $post_categories = wp_get_post_categories(get_the_ID()); $ad_categories = is_array($ad['categories']) ? $ad['categories'] : explode(',', $ad['categories']); $common_categories = array_intersect($post_categories, $ad_categories); $score += count($common_categories) * 0.5; } // 检查广告标签匹配 if (isset($ad['tags'])) { $post_tags = wp_get_post_tags(get_the_ID(), array('fields' => 'ids')); $ad_tags = is_array($ad['tags']) ? $ad['tags'] : explode(',', $ad['tags']); $common_tags = array_intersect($post_tags, $ad_tags); $score += count($common_tags) * 0.3; } if ($score > 0) { $ad['relevance_score'] = $score; $matched_ads[] = $ad; } } // 按相关性排序 usort($matched_ads, function($a, $b) { return $b['relevance_score'] <=> $a['relevance_score']; }); return $matched_ads; } /** * 获取内容匹配广告 * @param int $post_id 文章ID * @param int $limit 返回广告数量 * @return array 匹配的广告 */ public static function get_content_matched_ads($post_id = null, $limit = 3) { if (!$post_id) { $post_id = get_the_ID(); } // 提取关键词 $keywords = self::extract_keywords($post_id); // 获取所有活跃广告 $ads = self::get_active_ads(); // 匹配广告 $matched_ads = self::match_ads_by_keywords($keywords, $ads); // 限制返回数量 return array_slice($matched_ads, 0, $limit); } /** * 获取活跃广告 * @return array 广告数组 */ private static function get_active_ads() { global $wpdb; $table_name = $wpdb->prefix . 'ad_units'; $ads = $wpdb->get_results( "SELECT * FROM $table_name WHERE status = 'active'", ARRAY_A ); return $ads ?: array(); } } // 在文章页面使用 add_filter('the_content', function($content) { if (is_single()) { $matched_ads = ContentAwareAdMatcher::get_content_matched_ads(); if (!empty($matched_ads)) { $ad_html = '<div class="content-matched-ads">'; $ad_html .= '<h4>相关推荐</h4>'; foreach ($matched_ads as $ad) { $ad_html .= sprintf( '<div class="matched-ad" data-score="%.2f">%s</div>', $ad['relevance_score'], $ad['content'] ); } $ad_html .= '</div>'; // 在文章中间插入广告 $paragraphs = explode('</p>', $content); if (count($paragraphs) > 3) { $position = floor(count($paragraphs) / 2); array_splice($paragraphs, $position, 0, $ad_html); $content = implode('</p>', $paragraphs); } } } return $content; });
- 启用语义分析模块 // 在插件设置中启用语义分析 update_option('ad_semantic_analysis', true); // 配置语义分析参数 $semantic_config = array( 'min_relevance_score' => 0.3, 'max_ads_per_page' => 3, 'exclude_categories' => array(), // 排除的分类 'cache_duration' => 3600 // 缓存1小时 ); update_option('ad_semantic_config', $semantic_config); 训练关键词模型 /** * 广告关键词模型训练器 */ class AdKeywordModel { private static $model = array(); /** * 训练广告关键词模型 * @param array $training_data 训练数据 */ public static function train($training_data) { foreach ($training_data as $data) { $ad_id = $data['ad_id']; $keywords = $data['keywords']; $clicks = $data['clicks']; $impressions = $data['impressions']; // 计算关键词权重 $ctr = $impressions > 0 ? $clicks / $impressions : 0; foreach ($keywords as $keyword) { if (!isset(self::$model[$keyword])) { self::$model[$keyword] = array(); } if (!isset(self::$model[$keyword][$ad_id])) { self::$model[$keyword][$ad_id] = 0; } // 基于CTR更新权重 self::$model[$keyword][$ad_id] += $ctr * 100; } } // 保存模型 self::save_model(); } /** * 预测最佳广告 * @param array $page_keywords 页面关键词 * @return array 推荐广告 */ public static function predict($page_keywords) { $ad_scores = array(); foreach ($page_keywords as $keyword) { if (isset(self::$model[$keyword])) { foreach (self::$model[$keyword] as $ad_id => $score) { if (!isset($ad_scores[$ad_id])) { $ad_scores[$ad_id] = 0; } $ad_scores[$ad_id] += $score; } } } // 按分数排序 arsort($ad_scores); return $ad_scores; } /** * 保存模型到数据库 */ private static function save_model() { update_option('ad_keyword_model', self::$model); } /** * 加载模型 */ public static function load_model() { self::$model = get_option('ad_keyword_model', array()); } } // 定期训练模型 add_action('ad_model_training', function() { global $wpdb; // 获取历史数据 $training_data = $wpdb->get_results( "SELECT ad_id, keywords, clicks, impressions FROM {$wpdb->prefix}ad_performance WHERE impressions > 100", ARRAY_A ); if ($training_data) { AdKeywordModel::train($training_data); } }); // 每天训练一次 if (!wp_next_scheduled('ad_model_training')) { wp_schedule_event(time(), 'daily', 'ad_model_training'); }
-
- /** * 实时竞价系统集成 * 支持多个广告需求方平台(DSP) */ class RealTimeBiddingSystem { private $dsp_endpoints = array(); private $timeout = 200; // 毫秒 /** * 初始化DSP配置 */ public function __construct() { $this->dsp_endpoints = get_option('ad_dsp_endpoints', array( 'dsp1' => 'https://dsp1.example.com/bid', 'dsp2' => 'https://dsp2.example.com/auction' )); } /** * 发起实时竞价请求 * @param array $bid_request 竞价请求数据 * @return array 竞价结果 */ public function request_bids($bid_request) { $bids = array(); $promises = array(); // 准备请求数据 $request_data = array( 'id' => uniqid('bid_', true), 'imp' => array( array( 'id' => $bid_request['ad_unit_id'], 'banner' => array( 'w' => $bid_request['width'], 'h' => $bid_request['height'] ), 'bidfloor' => $bid_request['floor_price'] ?? 0.01 ) ), 'site' => array( 'domain' => $_SERVER['HTTP_HOST'], 'page' => $bid_request['page_url'] ), 'device' => array( 'ua' => $_SERVER['HTTP_USER_AGENT'], 'ip' => $_SERVER['REMOTE_ADDR'] ), 'user' => array( 'id' => $this->get_user_id() ) ); // 并发请求所有DSP foreach ($this->dsp_endpoints as $dsp_name => $endpoint) { $promises[$dsp_name] = $this->async_request($endpoint, $request_data); } // 等待所有响应(设置超时) $start_time = microtime(true); $responses = array(); while (!empty($promises) && (microtime(true) - $start_time) * 1000 < $this->timeout) { foreach ($promises as $dsp_name => $promise) { if ($this->is_request_complete($promise)) { $response = $this->get_response($promise); if ($response && isset($response['bid'])) { $responses[$dsp_name] = $response; } unset($promises[$dsp_name]); } } usleep(1000); // 等待1毫秒 } // 处理竞价结果 foreach ($responses as $dsp_name => $response) { foreach ($response['bid'] as $bid) { $bids[] = array( 'dsp' => $dsp_name, 'ad_id' => $bid['adid'], 'price' => $bid['price'], 'content' => $bid['adm'], 'creative_id' => $bid['crid'] ); } } // 按价格排序 usort($bids, function($a, $b) { return $b['price'] <=> $a['price']; }); return $bids; } /** * 异步HTTP请求 * @param string $url 请求URL * @param array $data 请求数据 * @return resource 请求句柄 */ private function async_request($url, $data) { $ch = curl_init($url); curl_setopt_array($ch, array( CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'Accept: application/json' ), CURLOPT_TIMEOUT_MS => $this->timeout, CURLOPT_NOSIGNAL => 1 )); // 异步执行(非阻塞) curl_multi_add_handle($this->multi_handle, $ch); return $ch; } /** * 获取用户标识 * @return string 用户ID */ private function get_user_id() { // 优先使用登录用户ID if ($user_id = get_current_user_id()) { return 'user_' . $user_id; } // 使用Cookie标识匿名用户 if (!isset($_COOKIE['ad_user_id'])) { $user_id = 'anon_' . md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']); setcookie('ad_user_id', $user_id, time() + 30 * DAY_IN_SECONDS, '/'); } else { $user_id = $_COOKIE['ad_user_id']; } return $user_id; } /** * 选择获胜竞价 * @param array $bids 竞价数组 * @return array 获胜的竞价 */ public function select_winning_bid($bids) { if (empty($bids)) { return null; } // 最高价获胜(第一次价格拍卖) $winning_bid = $bids[0]; // 记录竞价结果 $this->record_auction_result($winning_bid, $bids); // 通知获胜DSP $this->notify_winner($winning_bid); return $winning_bid; } /** * 记录竞价结果 */ private function record_auction_result($winner, $all_bids) { global $wpdb; $data = array( 'auction_id' => uniqid('auction_', true), 'winner_dsp' => $winner['dsp'], 'winner_price' => $winner['price'], 'second_price' => isset($bids[1]) ? $bids[1]['price'] : 0, 'total_bids' => count($all_bids), 'created_at' => current_time('mysql') ); $wpdb->insert($wpdb->prefix . 'ad_auctions', $data); } } // 使用实时竞价系统 add_action('wp_head', function() { if (is_single() || is_page()) { ?> <script> // 客户端竞价请求 function requestAdBid(adUnitId) { const bidRequest = { ad_unit_id: adUnitId, width: 728, height: 90, page_url: window.location.href }; fetch('/wp-json/ad/v1/bid', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(bidRequest) }) .then(response => response.json()) .then(data => { if (data.winner) { displayAd(data.winner.content); } }); } </script> <?php } }); // REST API端点 add_action('rest_api_init', function() { register_rest_route('ad/v1', '/bid', array( 'methods' => 'POST', 'callback' => function($request) { $bid_request = $request->get_json_params(); $rtb = new RealTimeBiddingSystem(); $bids = $rtb->request_bids($bid_request); $winner = $rtb->select_winning_bid($bids); return array( 'winner' => $winner, 'total_bids' => count($bids) ); }, 'permission_callback' => '__return_true' )); });
- /** * 动态定价引擎
-
在当今数字化营销时代,网络传媒广告的精准投放对于企业营销效果至关重要。WordPress作为全球最流行的内容管理系统,为广告投放提供了强大的平台支持。本文将详细介绍如何配置一款柔性广告投放WordPress插件,帮助您实现智能化、个性化的广告管理。
柔性广告投放插件是一款专为WordPress设计的智能广告管理系统,支持多种广告格式、定位方式和投放策略。它允许管理员根据访客特征、页面内容、时间因素等条件动态展示广告内容。
- 登录WordPress后台,进入"插件"→"安装插件"
- 在搜索框中输入"Flexible Ad Manager"
- 找到插件后点击"立即安装"
- 安装完成后点击"启用"
或者,您也可以手动安装:
- 下载插件ZIP文件
- 进入WordPress后台的"插件"→"安装插件"→"上传插件"
- 选择下载的ZIP文件并上传
- 启用插件
激活插件后,您会在WordPress侧边栏看到"广告管理"菜单。首次使用时,需要进行基础配置:
/**
* 广告插件基础配置示例代码
* 这段代码展示了如何初始化广告插件的基本设置
*/
// 定义广告系统常量
define('AD_SYSTEM_VERSION', '2.1.0');
define('AD_MAX_IMPRESSIONS', 10000); // 默认最大展示次数
define('AD_CLICK_LIMIT', 500); // 默认点击限制
class AdConfigInitializer {
/**
* 初始化广告插件配置
* @param array $options 配置选项数组
* @return bool 初始化是否成功
*/
public static function initialize($options = array()) {
// 默认配置
$defaults = array(
'enable_rotation' => true, // 启用广告轮播
'geo_targeting' => false, // 地理定位
'device_targeting' => true, // 设备定向
'time_targeting' => false, // 时间定向
'frequency_capping' => true, // 频次控制
'impressions_per_day' => 1000, // 每日展示上限
'default_ad_size' => '728x90', // 默认广告尺寸
'enable_analytics' => true // 启用分析功能
);
// 合并用户配置与默认配置
$config = wp_parse_args($options, $defaults);
// 保存配置到数据库
$result = update_option('flexible_ad_config', $config);
// 创建必要的数据库表
self::create_database_tables();
return $result;
}
/**
* 创建广告系统所需的数据库表
*/
private static function create_database_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
// 广告活动表
$campaigns_table = $wpdb->prefix . 'ad_campaigns';
$campaigns_sql = "CREATE TABLE IF NOT EXISTS $campaigns_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
start_date datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
end_date datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
budget decimal(10,2) DEFAULT 0.00,
status varchar(20) DEFAULT 'active',
targeting_rules text,
PRIMARY KEY (id)
) $charset_collate;";
// 广告单元表
$ad_units_table = $wpdb->prefix . 'ad_units';
$ad_units_sql = "CREATE TABLE IF NOT EXISTS $ad_units_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
campaign_id mediumint(9) NOT NULL,
title varchar(255) NOT NULL,
ad_type varchar(50) NOT NULL,
content text NOT NULL,
display_rules text,
impressions int DEFAULT 0,
clicks int DEFAULT 0,
weight int DEFAULT 1,
PRIMARY KEY (id),
KEY campaign_id (campaign_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($campaigns_sql);
dbDelta($ad_units_sql);
}
}
// 初始化配置示例
$initial_options = array(
'enable_rotation' => true,
'geo_targeting' => true, // 启用地理定位
'impressions_per_day' => 5000
);
AdConfigInitializer::initialize($initial_options);
在"广告管理"→"广告位"中,您可以创建和管理不同的广告位:
- 点击"添加新广告位"
- 输入广告位名称(如:首页横幅、文章内嵌等)
- 设置广告位尺寸和类型
- 配置展示规则(特定页面、分类等)
- 保存设置
地理定位允许您根据访客的地理位置展示不同的广告内容:
/**
* 地理定位广告示例
* 根据用户地理位置显示特定广告
*/
class GeoTargetingAd {
/**
* 根据地理位置获取适合的广告
* @param string $location 用户地理位置
* @param array $available_ads 可用广告数组
* @return array 匹配的广告
*/
public static function get_geo_targeted_ad($location, $available_ads) {
// 地理位置映射规则
$geo_rules = array(
'北京' => array('ad_1', 'ad_2', 'ad_3'),
'上海' => array('ad_4', 'ad_5'),
'广州' => array('ad_6', 'ad_7', 'ad_8'),
'深圳' => array('ad_9', 'ad_10'),
'default' => array('ad_default') // 默认广告
);
// 检查是否有特定地区的广告
if (isset($geo_rules[$location])) {
$targeted_ad_ids = $geo_rules[$location];
} else {
$targeted_ad_ids = $geo_rules['default'];
}
// 过滤出符合条件的广告
$filtered_ads = array();
foreach ($available_ads as $ad) {
if (in_array($ad['id'], $targeted_ad_ids)) {
$filtered_ads[] = $ad;
}
}
// 如果没有找到特定广告,返回默认广告
if (empty($filtered_ads)) {
foreach ($available_ads as $ad) {
if (in_array($ad['id'], $geo_rules['default'])) {
$filtered_ads[] = $ad;
}
}
}
return $filtered_ads;
}
/**
* 获取用户地理位置(简化示例)
* 实际应用中可能需要使用IP定位服务
* @return string 地理位置
*/
public static function detect_user_location() {
// 这里可以使用第三方IP定位API
// 简化示例:从cookie或session中获取
if (isset($_COOKIE['user_location'])) {
return sanitize_text_field($_COOKIE['user_location']);
}
// 默认位置
return 'default';
}
}
// 使用示例
$user_location = GeoTargetingAd::detect_user_location();
$available_ads = array(
array('id' => 'ad_1', 'content' => '北京地区专属广告'),
array('id' => 'ad_4', 'content' => '上海地区专属广告'),
array('id' => 'ad_default', 'content' => '默认广告内容')
);
$targeted_ads = GeoTargetingAd::get_geo_targeted_ad($user_location, $available_ads);
行为定向基于用户的历史行为展示相关广告:
- 进入"广告管理"→"行为定向"
- 创建行为规则(如:浏览过产品页的用户)
- 设置触发条件和展示广告
- 配置重定向频率和持续时间
广告轮播确保多个广告公平展示:
/**
* 智能广告轮播系统
* 支持权重控制和频次限制
*/
class AdRotator {
/**
* 根据权重选择广告
* @param array $ads 广告数组,包含权重信息
* @return array 选中的广告
*/
public static function select_ad_by_weight($ads) {
if (empty($ads)) {
return null;
}
// 计算总权重
$total_weight = 0;
foreach ($ads as $ad) {
$total_weight += isset($ad['weight']) ? $ad['weight'] : 1;
}
// 生成随机数
$random = mt_rand(1, $total_weight);
// 根据权重选择广告
$current_weight = 0;
foreach ($ads as $ad) {
$ad_weight = isset($ad['weight']) ? $ad['weight'] : 1;
$current_weight += $ad_weight;
if ($random <= $current_weight) {
return $ad;
}
}
// 如果未选中,返回第一个广告
return $ads[0];
}
/**
* 频次控制:检查广告是否可展示
* @param string $ad_id 广告ID
* @param string $user_id 用户标识
* @param int $max_impressions 最大展示次数
* @return bool 是否可以展示
*/
public static function check_frequency($ad_id, $user_id, $max_impressions = 3) {
// 获取用户广告展示记录
$user_ad_key = 'user_ad_impressions_' . $user_id;
$impressions = get_transient($user_ad_key);
if (!$impressions) {
$impressions = array();
}
// 检查该广告的展示次数
$ad_impressions = isset($impressions[$ad_id]) ? $impressions[$ad_id] : 0;
// 如果超过限制,返回false
if ($ad_impressions >= $max_impressions) {
return false;
}
// 更新展示次数
$impressions[$ad_id] = $ad_impressions + 1;
set_transient($user_ad_key, $impressions, DAY_IN_SECONDS); // 24小时有效
return true;
}
}
// 使用示例
$ads = array(
array('id' => 'ad_1', 'content' => '广告1', 'weight' => 3),
array('id' => 'ad_2', 'content' => '广告2', 'weight' => 2),
array('id' => 'ad_3', 'content' => '广告3', 'weight' => 1)
);
// 选择广告
$selected_ad = AdRotator::select_ad_by_weight($ads);
// 检查频次
$user_id = get_current_user_id() ?: $_SERVER['REMOTE_ADDR'];
if (AdRotator::check_frequency($selected_ad['id'], $user_id, 5)) {
// 展示广告
echo $selected_ad['content'];
}
- 进入"广告管理"→"频次控制"
- 设置每个用户每天看到同一广告的最大次数
- 配置时间窗口(小时、天、周)
- 设置例外规则(如VIP用户不受限制)
插件内置数据分析功能,您也可以集成第三方分析工具:
/**
* 广告效果跟踪器
* 记录展示、点击和转化数据
*/
class AdPerformanceTracker {
/**
* 记录广告展示
* @param string $ad_id 广告ID
* @param string $page_url 页面URL
* @param string $user_agent 用户代理
*/
public static function track_impression($ad_id, $page_url = '', $user_agent = '') {
global $wpdb;
$table_name = $wpdb->prefix . 'ad_statistics';
$data = array(
'ad_id' => $ad_id,
'event_type' => 'impression',
'page_url' => $page_url ?: $_SERVER['REQUEST_URI'],
'user_agent' => $user_agent ?: $_SERVER['HTTP_USER_AGENT'],
'ip_address' => $_SERVER['REMOTE_ADDR'],
'created_at' => current_time('mysql')
);
$wpdb->insert($table_name, $data);
// 更新广告单元的总展示数
self::update_ad_unit_stats($ad_id, 'impressions');
}
/**
* 记录广告点击
* @param string $ad_id 广告ID
* @param string $referrer 来源页面
*/
public static function track_click($ad_id, $referrer = '') {
global $wpdb;
$table_name = $wpdb->prefix . 'ad_statistics';
$data = array(
'ad_id' => $ad_id,
'event_type' => 'click',
'page_url' => $referrer ?: $_SERVER['HTTP_REFERER'],
'ip_address' => $_SERVER['REMOTE_ADDR'],
'created_at' => current_time('mysql')
);
$wpdb->insert($table_name, $data);
// 更新广告单元的总点击数
self::update_ad_unit_stats($ad_id, 'clicks');
}
/**
* 更新广告单元统计
* @param string $ad_id 广告ID
* @param string $field 要更新的字段
*/
private static function update_ad_unit_stats($ad_id, $field) {
global $wpdb;
$table_name = $wpdb->prefix . 'ad_units';
$wpdb->query(
$wpdb->prepare(
"UPDATE $table_name SET $field = $field + 1 WHERE id = %d",
$ad_id
)
);
}
/**
* 获取广告效果报告
* @param string $ad_id 广告ID
* @param string $start_date 开始日期
* @param string $end_date 结束日期
* @return array 统计数据
*/
public static function get_performance_report($ad_id = '', $start_date = '', $end_date = '') {
global $wpdb;
$table_name = $wpdb->prefix . 'ad_statistics';
$where_clause = '1=1';
$prepare_args = array();
if ($ad_id) {
$where_clause .= ' AND ad_id = %s';
$prepare_args[] = $ad_id;
}
if ($start_date) {
$where_clause .= ' AND created_at >= %s';
$prepare_args[] = $start_date;
}
if ($end_date) {
$where_clause .= ' AND created_at <= %s';
$prepare_args[] = $end_date;
}
$query = "SELECT
ad_id,
SUM(CASE WHEN event_type = 'impression' THEN 1 ELSE 0 END) as impressions,
SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) as clicks,
COUNT(DISTINCT ip_address) as unique_visitors
FROM $table_name
WHERE $where_clause
GROUP BY ad_id";
if (!empty($prepare_args)) {
$query = $wpdb->prepare($query, $prepare_args);
}
$results = $wpdb->get_results($query, ARRAY_A);
// 计算点击率
foreach ($results as &$row) {
if ($row['impressions'] > 0) {
$row['ctr'] = round(($row['clicks'] / $row['impressions']) * 100, 2);
} else {
$row['ctr'] = 0;
}
}
return $results;
}
}
// 使用示例:在广告展示时调用
AdPerformanceTracker::track_impression('ad_123', 'https://example.com/page');
// 在广告点击时调用(通常通过AJAX)
add_action('wp_ajax_track_ad_click', function() {
$ad_id = isset($_POST['ad_id']) ? sanitize_text_field($_POST['ad_id']) : '';
if ($ad_id) {
AdPerformanceTracker::track_click($ad_id);
wp_die('success');
}
});
- 创建广告变体(不同标题、图片或呼吁用语)
- 设置测试参数(样本大小、测试时长)
- 定义成功指标(点击率、转化率)
- 启动测试并监控结果
- 广告不显示:检查广告位设置、定向规则和广告状态
- 统计不准确:确保跟踪代码正确安装,检查缓存设置
- 性能问题:优化数据库查询,启用缓存,减少插件数量
- 启用广告缓存,减少数据库查询
- 使用CDN分发广告素材
- 压缩广告图片,优化加载速度
- 定期清理旧统计数据
- 定期更新插件到最新版本
- 验证所有广告代码,防止恶意脚本
- 限制广告上传文件类型
- 使用非管理员账户管理广告
通过合理配置柔性广告投放WordPress插件,您可以实现高度定制化的广告展示策略,提升广告效果
动态内容匹配技术能够分析页面内容并展示相关广告,大幅提升广告相关性和点击率:
/**
* 内容智能匹配广告系统
* 分析页面内容关键词并匹配相关广告
*/
class ContentAwareAdMatcher {
/**
* 提取页面关键词
* @param int $post_id 文章ID
* @return array 关键词数组
*/
public static function extract_keywords($post_id) {
$post = get_post($post_id);
if (!$post) {
return array();
}
// 获取文章内容
$content = $post->post_content . ' ' . $post->post_title;
// 移除HTML标签和短代码
$content = wp_strip_all_tags($content);
$content = strip_shortcodes($content);
// 分词处理(简化版,实际可使用NLP库)
$words = str_word_count($content, 1);
// 移除停用词
$stop_words = array('的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这');
$words = array_diff($words, $stop_words);
// 统计词频
$word_freq = array_count_values($words);
// 按频率排序并取前10个关键词
arsort($word_freq);
$keywords = array_slice(array_keys($word_freq), 0, 10);
return $keywords;
}
/**
* 匹配相关广告
* @param array $keywords 关键词数组
* @param array $ads 广告数组
* @return array 匹配的广告
*/
public static function match_ads_by_keywords($keywords, $ads) {
$matched_ads = array();
foreach ($ads as $ad) {
$score = 0;
// 检查广告关键词匹配
if (isset($ad['keywords'])) {
$ad_keywords = is_array($ad['keywords']) ? $ad['keywords'] : explode(',', $ad['keywords']);
foreach ($keywords as $keyword) {
foreach ($ad_keywords as $ad_keyword) {
// 使用相似度算法(简化版)
similar_text(strtolower($keyword), strtolower($ad_keyword), $percent);
if ($percent > 80) { // 相似度超过80%
$score += $percent / 100;
}
}
}
}
// 检查广告分类匹配
if (isset($ad['categories'])) {
$post_categories = wp_get_post_categories(get_the_ID());
$ad_categories = is_array($ad['categories']) ? $ad['categories'] : explode(',', $ad['categories']);
$common_categories = array_intersect($post_categories, $ad_categories);
$score += count($common_categories) * 0.5;
}
// 检查广告标签匹配
if (isset($ad['tags'])) {
$post_tags = wp_get_post_tags(get_the_ID(), array('fields' => 'ids'));
$ad_tags = is_array($ad['tags']) ? $ad['tags'] : explode(',', $ad['tags']);
$common_tags = array_intersect($post_tags, $ad_tags);
$score += count($common_tags) * 0.3;
}
if ($score > 0) {
$ad['relevance_score'] = $score;
$matched_ads[] = $ad;
}
}
// 按相关性排序
usort($matched_ads, function($a, $b) {
return $b['relevance_score'] <=> $a['relevance_score'];
});
return $matched_ads;
}
/**
* 获取内容匹配广告
* @param int $post_id 文章ID
* @param int $limit 返回广告数量
* @return array 匹配的广告
*/
public static function get_content_matched_ads($post_id = null, $limit = 3) {
if (!$post_id) {
$post_id = get_the_ID();
}
// 提取关键词
$keywords = self::extract_keywords($post_id);
// 获取所有活跃广告
$ads = self::get_active_ads();
// 匹配广告
$matched_ads = self::match_ads_by_keywords($keywords, $ads);
// 限制返回数量
return array_slice($matched_ads, 0, $limit);
}
/**
* 获取活跃广告
* @return array 广告数组
*/
private static function get_active_ads() {
global $wpdb;
$table_name = $wpdb->prefix . 'ad_units';
$ads = $wpdb->get_results(
"SELECT * FROM $table_name WHERE status = 'active'",
ARRAY_A
);
return $ads ?: array();
}
}
// 在文章页面使用
add_filter('the_content', function($content) {
if (is_single()) {
$matched_ads = ContentAwareAdMatcher::get_content_matched_ads();
if (!empty($matched_ads)) {
$ad_html = '<div class="content-matched-ads">';
$ad_html .= '<h4>相关推荐</h4>';
foreach ($matched_ads as $ad) {
$ad_html .= sprintf(
'<div class="matched-ad" data-score="%.2f">%s</div>',
$ad['relevance_score'],
$ad['content']
);
}
$ad_html .= '</div>';
// 在文章中间插入广告
$paragraphs = explode('</p>', $content);
if (count($paragraphs) > 3) {
$position = floor(count($paragraphs) / 2);
array_splice($paragraphs, $position, 0, $ad_html);
$content = implode('</p>', $paragraphs);
}
}
}
return $content;
});
-
启用语义分析模块
// 在插件设置中启用语义分析
update_option('ad_semantic_analysis', true);
// 配置语义分析参数
$semantic_config = array(
'min_relevance_score' => 0.3,
'max_ads_per_page' => 3,
'exclude_categories' => array(), // 排除的分类
'cache_duration' => 3600 // 缓存1小时
);
update_option('ad_semantic_config', $semantic_config);
-
训练关键词模型
/**
* 广告关键词模型训练器
*/
class AdKeywordModel {
private static $model = array();
/**
* 训练广告关键词模型
* @param array $training_data 训练数据
*/
public static function train($training_data) {
foreach ($training_data as $data) {
$ad_id = $data['ad_id'];
$keywords = $data['keywords'];
$clicks = $data['clicks'];
$impressions = $data['impressions'];
// 计算关键词权重
$ctr = $impressions > 0 ? $clicks / $impressions : 0;
foreach ($keywords as $keyword) {
if (!isset(self::$model[$keyword])) {
self::$model[$keyword] = array();
}
if (!isset(self::$model[$keyword][$ad_id])) {
self::$model[$keyword][$ad_id] = 0;
}
// 基于CTR更新权重
self::$model[$keyword][$ad_id] += $ctr * 100;
}
}
// 保存模型
self::save_model();
}
/**
* 预测最佳广告
* @param array $page_keywords 页面关键词
* @return array 推荐广告
*/
public static function predict($page_keywords) {
$ad_scores = array();
foreach ($page_keywords as $keyword) {
if (isset(self::$model[$keyword])) {
foreach (self::$model[$keyword] as $ad_id => $score) {
if (!isset($ad_scores[$ad_id])) {
$ad_scores[$ad_id] = 0;
}
$ad_scores[$ad_id] += $score;
}
}
}
// 按分数排序
arsort($ad_scores);
return $ad_scores;
}
/**
* 保存模型到数据库
*/
private static function save_model() {
update_option('ad_keyword_model', self::$model);
}
/**
* 加载模型
*/
public static function load_model() {
self::$model = get_option('ad_keyword_model', array());
}
}
// 定期训练模型
add_action('ad_model_training', function() {
global $wpdb;
// 获取历史数据
$training_data = $wpdb->get_results(
"SELECT ad_id, keywords, clicks, impressions
FROM {$wpdb->prefix}ad_performance
WHERE impressions > 100",
ARRAY_A
);
if ($training_data) {
AdKeywordModel::train($training_data);
}
});
// 每天训练一次
if (!wp_next_scheduled('ad_model_training')) {
wp_schedule_event(time(), 'daily', 'ad_model_training');
}
启用语义分析模块
// 在插件设置中启用语义分析
update_option('ad_semantic_analysis', true);
// 配置语义分析参数
$semantic_config = array(
'min_relevance_score' => 0.3,
'max_ads_per_page' => 3,
'exclude_categories' => array(), // 排除的分类
'cache_duration' => 3600 // 缓存1小时
);
update_option('ad_semantic_config', $semantic_config);
训练关键词模型
/**
* 广告关键词模型训练器
*/
class AdKeywordModel {
private static $model = array();
/**
* 训练广告关键词模型
* @param array $training_data 训练数据
*/
public static function train($training_data) {
foreach ($training_data as $data) {
$ad_id = $data['ad_id'];
$keywords = $data['keywords'];
$clicks = $data['clicks'];
$impressions = $data['impressions'];
// 计算关键词权重
$ctr = $impressions > 0 ? $clicks / $impressions : 0;
foreach ($keywords as $keyword) {
if (!isset(self::$model[$keyword])) {
self::$model[$keyword] = array();
}
if (!isset(self::$model[$keyword][$ad_id])) {
self::$model[$keyword][$ad_id] = 0;
}
// 基于CTR更新权重
self::$model[$keyword][$ad_id] += $ctr * 100;
}
}
// 保存模型
self::save_model();
}
/**
* 预测最佳广告
* @param array $page_keywords 页面关键词
* @return array 推荐广告
*/
public static function predict($page_keywords) {
$ad_scores = array();
foreach ($page_keywords as $keyword) {
if (isset(self::$model[$keyword])) {
foreach (self::$model[$keyword] as $ad_id => $score) {
if (!isset($ad_scores[$ad_id])) {
$ad_scores[$ad_id] = 0;
}
$ad_scores[$ad_id] += $score;
}
}
}
// 按分数排序
arsort($ad_scores);
return $ad_scores;
}
/**
* 保存模型到数据库
*/
private static function save_model() {
update_option('ad_keyword_model', self::$model);
}
/**
* 加载模型
*/
public static function load_model() {
self::$model = get_option('ad_keyword_model', array());
}
}
// 定期训练模型
add_action('ad_model_training', function() {
global $wpdb;
// 获取历史数据
$training_data = $wpdb->get_results(
"SELECT ad_id, keywords, clicks, impressions
FROM {$wpdb->prefix}ad_performance
WHERE impressions > 100",
ARRAY_A
);
if ($training_data) {
AdKeywordModel::train($training_data);
}
});
// 每天训练一次
if (!wp_next_scheduled('ad_model_training')) {
wp_schedule_event(time(), 'daily', 'ad_model_training');
}
/**
* 实时竞价系统集成
* 支持多个广告需求方平台(DSP)
*/
class RealTimeBiddingSystem {
private $dsp_endpoints = array();
private $timeout = 200; // 毫秒
/**
* 初始化DSP配置
*/
public function __construct() {
$this->dsp_endpoints = get_option('ad_dsp_endpoints', array(
'dsp1' => 'https://dsp1.example.com/bid',
'dsp2' => 'https://dsp2.example.com/auction'
));
}
/**
* 发起实时竞价请求
* @param array $bid_request 竞价请求数据
* @return array 竞价结果
*/
public function request_bids($bid_request) {
$bids = array();
$promises = array();
// 准备请求数据
$request_data = array(
'id' => uniqid('bid_', true),
'imp' => array(
array(
'id' => $bid_request['ad_unit_id'],
'banner' => array(
'w' => $bid_request['width'],
'h' => $bid_request['height']
),
'bidfloor' => $bid_request['floor_price'] ?? 0.01
)
),
'site' => array(
'domain' => $_SERVER['HTTP_HOST'],
'page' => $bid_request['page_url']
),
'device' => array(
'ua' => $_SERVER['HTTP_USER_AGENT'],
'ip' => $_SERVER['REMOTE_ADDR']
),
'user' => array(
'id' => $this->get_user_id()
)
);
// 并发请求所有DSP
foreach ($this->dsp_endpoints as $dsp_name => $endpoint) {
$promises[$dsp_name] = $this->async_request($endpoint, $request_data);
}
// 等待所有响应(设置超时)
$start_time = microtime(true);
$responses = array();
while (!empty($promises) && (microtime(true) - $start_time) * 1000 < $this->timeout) {
foreach ($promises as $dsp_name => $promise) {
if ($this->is_request_complete($promise)) {
$response = $this->get_response($promise);
if ($response && isset($response['bid'])) {
$responses[$dsp_name] = $response;
}
unset($promises[$dsp_name]);
}
}
usleep(1000); // 等待1毫秒
}
// 处理竞价结果
foreach ($responses as $dsp_name => $response) {
foreach ($response['bid'] as $bid) {
$bids[] = array(
'dsp' => $dsp_name,
'ad_id' => $bid['adid'],
'price' => $bid['price'],
'content' => $bid['adm'],
'creative_id' => $bid['crid']
);
}
}
// 按价格排序
usort($bids, function($a, $b) {
return $b['price'] <=> $a['price'];
});
return $bids;
}
/**
* 异步HTTP请求
* @param string $url 请求URL
* @param array $data 请求数据
* @return resource 请求句柄
*/
private function async_request($url, $data) {
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept: application/json'
),
CURLOPT_TIMEOUT_MS => $this->timeout,
CURLOPT_NOSIGNAL => 1
));
// 异步执行(非阻塞)
curl_multi_add_handle($this->multi_handle, $ch);
return $ch;
}
/**
* 获取用户标识
* @return string 用户ID
*/
private function get_user_id() {
// 优先使用登录用户ID
if ($user_id = get_current_user_id()) {
return 'user_' . $user_id;
}
// 使用Cookie标识匿名用户
if (!isset($_COOKIE['ad_user_id'])) {
$user_id = 'anon_' . md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
setcookie('ad_user_id', $user_id, time() + 30 * DAY_IN_SECONDS, '/');
} else {
$user_id = $_COOKIE['ad_user_id'];
}
return $user_id;
}
/**
* 选择获胜竞价
* @param array $bids 竞价数组
* @return array 获胜的竞价
*/
public function select_winning_bid($bids) {
if (empty($bids)) {
return null;
}
// 最高价获胜(第一次价格拍卖)
$winning_bid = $bids[0];
// 记录竞价结果
$this->record_auction_result($winning_bid, $bids);
// 通知获胜DSP
$this->notify_winner($winning_bid);
return $winning_bid;
}
/**
* 记录竞价结果
*/
private function record_auction_result($winner, $all_bids) {
global $wpdb;
$data = array(
'auction_id' => uniqid('auction_', true),
'winner_dsp' => $winner['dsp'],
'winner_price' => $winner['price'],
'second_price' => isset($bids[1]) ? $bids[1]['price'] : 0,
'total_bids' => count($all_bids),
'created_at' => current_time('mysql')
);
$wpdb->insert($wpdb->prefix . 'ad_auctions', $data);
}
}
// 使用实时竞价系统
add_action('wp_head', function() {
if (is_single() || is_page()) {
?>
<script>
// 客户端竞价请求
function requestAdBid(adUnitId) {
const bidRequest = {
ad_unit_id: adUnitId,
width: 728,
height: 90,
page_url: window.location.href
};
fetch('/wp-json/ad/v1/bid', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bidRequest)
})
.then(response => response.json())
.then(data => {
if (data.winner) {
displayAd(data.winner.content);
}
});
}
</script>
<?php
}
});
// REST API端点
add_action('rest_api_init', function() {
register_rest_route('ad/v1', '/bid', array(
'methods' => 'POST',
'callback' => function($request) {
$bid_request = $request->get_json_params();
$rtb = new RealTimeBiddingSystem();
$bids = $rtb->request_bids($bid_request);
$winner = $rtb->select_winning_bid($bids);
return array(
'winner' => $winner,
'total_bids' => count($bids)
);
},
'permission_callback' => '__return_true'
));
});
/**
* 实时竞价系统集成
* 支持多个广告需求方平台(DSP)
*/
class RealTimeBiddingSystem {
private $dsp_endpoints = array();
private $timeout = 200; // 毫秒
/**
* 初始化DSP配置
*/
public function __construct() {
$this->dsp_endpoints = get_option('ad_dsp_endpoints', array(
'dsp1' => 'https://dsp1.example.com/bid',
'dsp2' => 'https://dsp2.example.com/auction'
));
}
/**
* 发起实时竞价请求
* @param array $bid_request 竞价请求数据
* @return array 竞价结果
*/
public function request_bids($bid_request) {
$bids = array();
$promises = array();
// 准备请求数据
$request_data = array(
'id' => uniqid('bid_', true),
'imp' => array(
array(
'id' => $bid_request['ad_unit_id'],
'banner' => array(
'w' => $bid_request['width'],
'h' => $bid_request['height']
),
'bidfloor' => $bid_request['floor_price'] ?? 0.01
)
),
'site' => array(
'domain' => $_SERVER['HTTP_HOST'],
'page' => $bid_request['page_url']
),
'device' => array(
'ua' => $_SERVER['HTTP_USER_AGENT'],
'ip' => $_SERVER['REMOTE_ADDR']
),
'user' => array(
'id' => $this->get_user_id()
)
);
// 并发请求所有DSP
foreach ($this->dsp_endpoints as $dsp_name => $endpoint) {
$promises[$dsp_name] = $this->async_request($endpoint, $request_data);
}
// 等待所有响应(设置超时)
$start_time = microtime(true);
$responses = array();
while (!empty($promises) && (microtime(true) - $start_time) * 1000 < $this->timeout) {
foreach ($promises as $dsp_name => $promise) {
if ($this->is_request_complete($promise)) {
$response = $this->get_response($promise);
if ($response && isset($response['bid'])) {
$responses[$dsp_name] = $response;
}
unset($promises[$dsp_name]);
}
}
usleep(1000); // 等待1毫秒
}
// 处理竞价结果
foreach ($responses as $dsp_name => $response) {
foreach ($response['bid'] as $bid) {
$bids[] = array(
'dsp' => $dsp_name,
'ad_id' => $bid['adid'],
'price' => $bid['price'],
'content' => $bid['adm'],
'creative_id' => $bid['crid']
);
}
}
// 按价格排序
usort($bids, function($a, $b) {
return $b['price'] <=> $a['price'];
});
return $bids;
}
/**
* 异步HTTP请求
* @param string $url 请求URL
* @param array $data 请求数据
* @return resource 请求句柄
*/
private function async_request($url, $data) {
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept: application/json'
),
CURLOPT_TIMEOUT_MS => $this->timeout,
CURLOPT_NOSIGNAL => 1
));
// 异步执行(非阻塞)
curl_multi_add_handle($this->multi_handle, $ch);
return $ch;
}
/**
* 获取用户标识
* @return string 用户ID
*/
private function get_user_id() {
// 优先使用登录用户ID
if ($user_id = get_current_user_id()) {
return 'user_' . $user_id;
}
// 使用Cookie标识匿名用户
if (!isset($_COOKIE['ad_user_id'])) {
$user_id = 'anon_' . md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
setcookie('ad_user_id', $user_id, time() + 30 * DAY_IN_SECONDS, '/');
} else {
$user_id = $_COOKIE['ad_user_id'];
}
return $user_id;
}
/**
* 选择获胜竞价
* @param array $bids 竞价数组
* @return array 获胜的竞价
*/
public function select_winning_bid($bids) {
if (empty($bids)) {
return null;
}
// 最高价获胜(第一次价格拍卖)
$winning_bid = $bids[0];
// 记录竞价结果
$this->record_auction_result($winning_bid, $bids);
// 通知获胜DSP
$this->notify_winner($winning_bid);
return $winning_bid;
}
/**
* 记录竞价结果
*/
private function record_auction_result($winner, $all_bids) {
global $wpdb;
$data = array(
'auction_id' => uniqid('auction_', true),
'winner_dsp' => $winner['dsp'],
'winner_price' => $winner['price'],
'second_price' => isset($bids[1]) ? $bids[1]['price'] : 0,
'total_bids' => count($all_bids),
'created_at' => current_time('mysql')
);
$wpdb->insert($wpdb->prefix . 'ad_auctions', $data);
}
}
// 使用实时竞价系统
add_action('wp_head', function() {
if (is_single() || is_page()) {
?>
<script>
// 客户端竞价请求
function requestAdBid(adUnitId) {
const bidRequest = {
ad_unit_id: adUnitId,
width: 728,
height: 90,
page_url: window.location.href
};
fetch('/wp-json/ad/v1/bid', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bidRequest)
})
.then(response => response.json())
.then(data => {
if (data.winner) {
displayAd(data.winner.content);
}
});
}
</script>
<?php
}
});
// REST API端点
add_action('rest_api_init', function() {
register_rest_route('ad/v1', '/bid', array(
'methods' => 'POST',
'callback' => function($request) {
$bid_request = $request->get_json_params();
$rtb = new RealTimeBiddingSystem();
$bids = $rtb->request_bids($bid_request);
$winner = $rtb->select_winning_bid($bids);
return array(
'winner' => $winner,
'total_bids' => count($bids)
);
},
'permission_callback' => '__return_true'
));
});
/**
* 动态定价引擎
/**
* 动态定价引擎


