文章目录[隐藏]
WordPress柔性广告素材智能生成插件开发教程
一、插件概述与准备工作
1.1 什么是柔性广告素材智能生成插件
柔性广告素材智能生成插件是一款专为网络传媒行业设计的WordPress扩展工具,它能够根据不同的广告位尺寸、目标受众和内容主题,自动生成适配的广告素材。通过智能算法,插件可以动态调整广告的文字、图片和布局,大幅提高广告投放效率和转化率。
1.2 开发环境准备
在开始开发之前,请确保您的开发环境满足以下要求:
- WordPress 5.0+ 版本
- PHP 7.4+ 版本
- MySQL 5.6+ 或 MariaDB 10.1+
- 基本的HTML、CSS、JavaScript和PHP知识
<?php
/**
* 插件主文件 - flexible-ad-generator.php
*
* @package Flexible_Ad_Generator
* @version 1.0.0
*/
/*
Plugin Name: 柔性广告素材智能生成插件
Plugin URI: https://yourwebsite.com/flexible-ad-generator
Description: 智能生成适配不同广告位的柔性广告素材
Version: 1.0.0
Author: 您的名字
Author URI: https://yourwebsite.com
License: GPL v2 or later
Text Domain: flexible-ad-generator
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('FAG_VERSION', '1.0.0');
define('FAG_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FAG_PLUGIN_URL', plugin_dir_url(__FILE__));
二、插件基础架构搭建
2.1 创建插件目录结构
flexible-ad-generator/
├── flexible-ad-generator.php # 主插件文件
├── includes/ # 核心功能文件
│ ├── class-ad-generator.php # 广告生成器类
│ ├── class-ad-templates.php # 广告模板类
│ └── class-ai-processor.php # AI处理类
├── admin/ # 后台管理文件
│ ├── css/ # 后台样式
│ ├── js/ # 后台脚本
│ └── admin-pages.php # 管理页面
├── public/ # 前端文件
│ ├── css/ # 前端样式
│ ├── js/ # 前端脚本
│ └── shortcodes.php # 短代码处理
├── templates/ # 模板文件
│ ├── banner-ad.php # 横幅广告模板
│ ├── square-ad.php # 方形广告模板
│ └── vertical-ad.php # 垂直广告模板
└── assets/ # 静态资源
├── images/ # 默认图片
└── fonts/ # 字体文件
2.2 初始化插件功能
<?php
// includes/class-ad-generator.php
/**
* 广告生成器主类
*/
class Flexible_Ad_Generator {
private static $instance = null;
private $templates;
private $ai_processor;
/**
* 获取单例实例
*/
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 FAG_PLUGIN_DIR . 'includes/class-ad-templates.php';
require_once FAG_PLUGIN_DIR . 'includes/class-ai-processor.php';
$this->templates = new Ad_Templates();
$this->ai_processor = new AI_Processor();
}
/**
* 初始化WordPress钩子
*/
private function init_hooks() {
// 激活/停用插件时的操作
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
// 初始化
add_action('init', array($this, 'init'));
// 后台菜单
add_action('admin_menu', array($this, 'add_admin_menu'));
// 注册短代码
add_shortcode('flexible_ad', array($this, 'render_ad_shortcode'));
}
/**
* 插件激活时的操作
*/
public function activate() {
// 创建必要的数据库表
$this->create_database_tables();
// 设置默认选项
$this->set_default_options();
// 刷新重写规则
flush_rewrite_rules();
}
/**
* 创建数据库表
*/
private function create_database_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'flexible_ads';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
title varchar(255) NOT NULL,
ad_type varchar(50) NOT NULL,
dimensions varchar(50) NOT NULL,
content text NOT NULL,
styles text,
ai_settings text,
impressions int(11) DEFAULT 0,
clicks int(11) DEFAULT 0,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
}
三、智能广告生成核心功能
3.1 AI广告内容生成器
<?php
// includes/class-ai-processor.php
/**
* AI内容处理类
*/
class AI_Processor {
/**
* 根据关键词生成广告文案
*
* @param string $keywords 关键词
* @param string $tone 语气风格
* @param int $max_length 最大长度
* @return string 生成的文案
*/
public function generate_ad_copy($keywords, $tone = 'professional', $max_length = 200) {
// 这里可以集成第三方AI API,如OpenAI、百度AI等
// 以下为模拟实现
$tone_modifiers = array(
'professional' => array('高效', '专业', '可靠', '优质'),
'casual' => array('轻松', '简单', '有趣', '便捷'),
'urgent' => array('立即', '限时', '独家', '抢购')
);
$modifiers = isset($tone_modifiers[$tone]) ? $tone_modifiers[$tone] : $tone_modifiers['professional'];
$modifier = $modifiers[array_rand($modifiers)];
$action_verbs = array('发现', '体验', '获取', '享受', '探索', '开启');
$action_verb = $action_verbs[array_rand($action_verbs)];
$benefits = array('节省时间', '提高效率', '提升品质', '优化体验', '创造价值');
$benefit = $benefits[array_rand($benefits)];
// 构建广告文案
$copy = "{$modifier}{$keywords},{$action_verb}全新{$benefit}体验。";
// 如果文案太短,添加更多内容
if (strlen($copy) < $max_length * 0.5) {
$additional = array(
"立即行动,享受特别优惠!",
"限时特惠,机会不容错过!",
"专业团队,为您提供卓越服务。"
);
$copy .= " " . $additional[array_rand($additional)];
}
return mb_substr($copy, 0, $max_length);
}
/**
* 智能选择配色方案
*
* @param string $industry 行业类型
* @param string $mood 情绪氛围
* @return array 配色方案
*/
public function generate_color_scheme($industry, $mood = 'neutral') {
$schemes = array(
'technology' => array(
'primary' => '#2563eb',
'secondary' => '#1e40af',
'accent' => '#3b82f6',
'text' => '#1f2937',
'background' => '#f8fafc'
),
'fashion' => array(
'primary' => '#ec4899',
'secondary' => '#be185d',
'accent' => '#f472b6',
'text' => '#4c0519',
'background' => '#fdf2f8'
),
'food' => array(
'primary' => '#f59e0b',
'secondary' => '#d97706',
'accent' => '#fbbf24',
'text' => '#78350f',
'background' => '#fffbeb'
)
);
// 根据情绪调整亮度
$base_scheme = isset($schemes[$industry]) ? $schemes[$industry] : $schemes['technology'];
if ($mood === 'bright') {
// 提高亮度
$base_scheme['primary'] = $this->adjust_brightness($base_scheme['primary'], 30);
$base_scheme['background'] = '#ffffff';
} elseif ($mood === 'dark') {
// 暗色模式
$base_scheme['primary'] = $this->adjust_brightness($base_scheme['primary'], -20);
$base_scheme['background'] = '#1f2937';
$base_scheme['text'] = '#f9fafb';
}
return $base_scheme;
}
/**
* 调整颜色亮度
*/
private function adjust_brightness($hex, $percent) {
// 颜色亮度调整逻辑
// 这里简化实现,实际应用中需要完整的颜色处理函数
return $hex;
}
}
3.2 广告模板系统
<?php
// includes/class-ad-templates.php
/**
* 广告模板管理类
*/
class Ad_Templates {
private $templates = array();
public function __construct() {
$this->load_templates();
}
/**
* 加载所有模板
*/
private function load_templates() {
$this->templates = array(
'banner' => array(
'name' => '横幅广告',
'dimensions' => array(
'728x90' => array('width' => 728, 'height' => 90),
'970x250' => array('width' => 970, 'height' => 250),
'320x100' => array('width' => 320, 'height' => 100)
),
'template_file' => 'banner-ad.php'
),
'square' => array(
'name' => '方形广告',
'dimensions' => array(
'300x250' => array('width' => 300, 'height' => 250),
'250x250' => array('width' => 250, 'height' => 250),
'200x200' => array('width' => 200, 'height' => 200)
),
'template_file' => 'square-ad.php'
),
'vertical' => array(
'name' => '垂直广告',
'dimensions' => array(
'300x600' => array('width' => 300, 'height' => 600),
'160x600' => array('width' => 160, 'height' => 600)
),
'template_file' => 'vertical-ad.php'
)
);
}
/**
* 渲染广告模板
*
* @param string $type 广告类型
* @param array $data 广告数据
* @return string 渲染后的HTML
*/
public function render($type, $data) {
if (!isset($this->templates[$type])) {
return '<p>广告模板不存在</p>';
}
$template_file = FAG_PLUGIN_DIR . 'templates/' . $this->templates[$type]['template_file'];
if (!file_exists($template_file)) {
return '<p>模板文件不存在</p>';
}
// 提取变量
extract($data);
// 开始输出缓冲
ob_start();
// 包含模板文件
include($template_file);
// 获取缓冲内容
$output = ob_get_clean();
return $output;
}
/**
* 获取所有可用模板
*/
public function get_all_templates() {
return $this->templates;
}
}
四、前端广告展示与短代码
4.1 广告短代码实现
<?php
// public/shortcodes.php
/**
* 广告短代码渲染
*
* @param array $atts 短代码属性
* @param string $content 短代码内容
* @return string 广告HTML
*/
function fag_render_ad_shortcode($atts, $content = null) {
// 默认属性
$atts = shortcode_atts(array(
'type' => 'banner',
'size' => '728x90',
'title' => '智能广告',
'text' => '',
'image' => '',
'link' => '#',
'bg_color' => '',
'text_color' => '',
'button_text' => '了解更多',
'animation' => 'fade'
), $atts, 'flexible_ad');
// 获取广告生成器实例
$ad_generator = Flexible_Ad_Generator::get_instance();
// 如果没有提供文案,使用AI生成
if (empty($atts['text'])) {
$ai_processor = new AI_Processor();
$keywords = !empty($content) ? $content : '优质服务';
$atts['text'] = $ai_processor->generate_ad_copy($keywords);
}
// 如果没有提供颜色,使用AI生成配色方案
if (empty($atts['bg_color']) || empty($atts['text_color'])) {
$ai_processor = new AI_Processor();
$color_scheme = $ai_processor->generate_color_scheme('technology');
$atts['bg_color'] = $color_scheme['background'];
$atts['text_color'] = $color_scheme['text'];
}
// 构建广告数据
$ad_data = array(
'title' => $atts['title'],
'text' => $atts['text'],
'image' => $atts['image'],
'link' => $atts['link'],
'bg_color' => $atts['bg_color'],
'text_color' => $atts['text_color'],
'button_text' => $atts['button_text'],
'animation' => $atts['animation'],
'dimensions' => $atts['size']
);
// 获取模板类实例
$templates = new Ad_Templates();
// 渲染广告
$ad_html = $templates->render($atts['type'], $ad_data);
// 添加跟踪代码
$ad_id = uniqid('ad_');
$ad_html = '<div id="' . $ad_id . '" class="flexible-ad-container" data-ad-id="' . $ad_id . '">' . $ad_html . '</div>';
// 添加JavaScript跟踪
$ad_html .= '<script>
document.addEventListener("DOMContentLoaded", function() {
var adElement = document.getElementById("' . $ad_id . '");
if (adElement) {
// 记录展示
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
// 发送展示统计(实际应用中应使用AJAX)
console.log("广告展示: ' . $ad_id . '");
observer.unobserve(entry.target);
}
});
}, { threshold: 0.5 });
observer.observe(adElement);
// 点击跟踪
adElement.addEventListener("click", function(e) {
if (e.target.tagName === "A" || e.target.closest("a")) {
console.log("广告点击: ' . $ad_id . '");
}
});
}
});
</script>';
return $ad_html;
}
// 注册短代码
add_shortcode('flexible_ad', 'fag_render_ad_shortcode');
4.2 广告模板示例
<?php
/* templates/banner-ad.php */
/**
* 横幅广告模板
*/
// 解析尺寸
list($width, $height) = explode('x', $dimensions);
?>
<div class="flexible-ad flexible-ad-banner"
style="width: <?php echo $width; ?>px; height: <?php echo $height; ?>px;
background-color: <?php echo $bg_color; ?>;
color: <?php echo $text_color; ?>;
position: relative;
overflow: hidden;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
transition: transform 0.3s ease;
margin: 10px auto;">
<?php if (!empty($image)): ?>
<div class="ad-image" style="position: absolute; right: 20px; top: 50%; transform: translateY(-50%);">
<img src="<?php echo $image; ?>" alt="<?php echo esc_attr($title); ?>"
echo $height - 20; ?>px; max-width: 150px; border-radius: 4px;">
</div>
<?php endif; ?>
<div class="ad-content" style="padding: 15px; max-width: <?php echo empty($image) ? '100%' : '70%'; ?>;">
<h3 class="ad-title" style="margin: 0 0 8px 0; font-size: 18px; font-weight: bold;">
<?php echo esc_html($title); ?>
</h3>
<p class="ad-text" style="margin: 0 0 12px 0; font-size: 14px; line-height: 1.4;">
<?php echo esc_html($text); ?>
</p>
<a href="<?php echo esc_url($link); ?>"
class="ad-button"
target="_blank"
rel="noopener noreferrer"
style="display: inline-block;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 8px 16px;
border-radius: 4px;
text-decoration: none;
font-weight: bold;
font-size: 14px;
transition: all 0.3s ease;">
<?php echo esc_html($button_text); ?>
</a>
</div>
<div class="ad-badge" style="position: absolute; top: 8px; right: 8px;
background: rgba(0,0,0,0.1); color: <?php echo $text_color; ?>;
padding: 2px 6px; border-radius: 3px; font-size: 10px;">
广告
</div>
</div>
<style>
.flexible-ad-banner:hover {
transform: translateY(-2px);
box-shadow: 0 6px 12px rgba(0,0,0,0.15);
}
.flexible-ad-banner .ad-button:hover {
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
}
</style>
## 五、后台管理界面开发
### 5.1 管理菜单和页面
<?php
// admin/admin-pages.php
/**
- 添加管理菜单
*/
function fag_add_admin_menu() {
add_menu_page(
'柔性广告生成器',
'广告生成器',
'manage_options',
'flexible-ad-generator',
'fag_render_admin_dashboard',
'dashicons-megaphone',
30
);
add_submenu_page(
'flexible-ad-generator',
'创建新广告',
'创建广告',
'manage_options',
'fag-create-ad',
'fag_render_create_ad_page'
);
add_submenu_page(
'flexible-ad-generator',
'广告库',
'广告库',
'manage_options',
'fag-ad-library',
'fag_render_ad_library'
);
add_submenu_page(
'flexible-ad-generator',
'AI设置',
'AI设置',
'manage_options',
'fag-ai-settings',
'fag_render_ai_settings'
);
add_submenu_page(
'flexible-ad-generator',
'统计数据',
'统计数据',
'manage_options',
'fag-analytics',
'fag_render_analytics'
);
}
add_action('admin_menu', 'fag_add_admin_menu');
/**
- 渲染主仪表板
*/
function fag_render_admin_dashboard() {
?>
<div class="wrap fag-dashboard">
<h1><?php echo esc_html__('柔性广告素材智能生成器', 'flexible-ad-generator'); ?></h1>
<div class="fag-stats-container" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin: 20px 0;">
<div class="fag-stat-card" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h3>总广告数</h3>
<p class="stat-number" style="font-size: 36px; font-weight: bold; color: #4CAF50;"><?php echo fag_get_total_ads_count(); ?></p>
</div>
<div class="fag-stat-card" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h3>今日展示</h3>
<p class="stat-number" style="font-size: 36px; font-weight: bold; color: #2196F3;"><?php echo fag_get_today_impressions(); ?></p>
</div>
<div class="fag-stat-card" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h3>点击率</h3>
<p class="stat-number" style="font-size: 36px; font-weight: bold; color: #FF9800;"><?php echo fag_get_ctr() . '%'; ?></p>
</div>
</div>
<div class="fag-quick-actions" style="margin: 30px 0;">
<h2>快速操作</h2>
<div style="display: flex; gap: 10px; margin-top: 15px;">
<a href="<?php echo admin_url('admin.php?page=fag-create-ad'); ?>" class="button button-primary" style="padding: 12px 24px;">
创建新广告
</a>
<a href="<?php echo admin_url('admin.php?page=fag-ad-library'); ?>" class="button" style="padding: 12px 24px;">
查看广告库
</a>
<a href="<?php echo admin_url('admin.php?page=fag-analytics'); ?>" class="button" style="padding: 12px 24px;">
查看统计数据
</a>
</div>
</div>
<div class="fag-recent-ads" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h2>最近创建的广告</h2>
<?php fag_render_recent_ads_table(); ?>
</div>
</div>
<?php
}
/**
- 渲染创建广告页面
*/
function fag_render_create_ad_page() {
// 获取模板选项
$templates = new Ad_Templates();
$all_templates = $templates->get_all_templates();
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fag_create_ad'])) {
fag_handle_create_ad($_POST);
}
?>
<div class="wrap">
<h1>创建新广告</h1>
<form method="POST" action="" id="fag-create-ad-form">
<?php wp_nonce_field('fag_create_ad', 'fag_nonce'); ?>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-top: 20px;">
<!-- 左侧:基本设置 -->
<div>
<h2>基本设置</h2>
<table class="form-table">
<tr>
<th scope="row"><label for="ad_title">广告标题</label></th>
<td>
<input type="text" id="ad_title" name="ad_title" class="regular-text"
value="" required>
<p class="description">广告的主要标题</p>
</td>
</tr>
<tr>
<th scope="row"><label for="ad_type">广告类型</label></th>
<td>
<select id="ad_type" name="ad_type" class="regular-text" onchange="fagUpdateDimensions()">
<?php foreach ($all_templates as $key => $template): ?>
<option value="<?php echo esc_attr($key); ?>">
<?php echo esc_html($template['name']); ?>
</option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th scope="row"><label for="ad_dimensions">广告尺寸</label></th>
<td>
<select id="ad_dimensions" name="ad_dimensions" class="regular-text">
<!-- 通过JavaScript动态填充 -->
</select>
</td>
</tr>
<tr>
<th scope="row"><label for="target_url">目标链接</label></th>
<td>
<input type="url" id="target_url" name="target_url" class="regular-text"
value="" required>
</td>
</tr>
</table>
<h2>AI智能生成</h2>
<table class="form-table">
<tr>
<th scope="row"><label for="ai_keywords">关键词</label></th>
<td>
<input type="text" id="ai_keywords" name="ai_keywords" class="regular-text"
placeholder="例如:科技产品、优惠促销">
<button type="button" class="button" onclick="fagGenerateContent()">
生成文案
</button>
</td>
</tr>
<tr>
<th scope="row"><label for="tone_style">语气风格</label></th>
<td>
<select id="tone_style" name="tone_style" class="regular-text">
<option value="professional">专业正式</option>
<option value="casual">轻松随意</option>
<option value="urgent">紧急促销</option>
<option value="friendly">友好亲切</option>
</select>
</td>
</tr>
<tr>
<th scope="row"><label for="color_scheme">配色方案</label></th>
<td>
<select id="color_scheme" name="color_scheme" class="regular-text">
<option value="auto">自动选择</option>
<option value="technology">科技蓝</option>
<option value="fashion">时尚粉</option>
<option value="food">食品橙</option>
<option value="finance">金融绿</option>
</select>
<button type="button" class="button" onclick="fagGenerateColors()">
生成配色
</button>
</td>
</tr>
</table>
</div>
<!-- 右侧:内容编辑和预览 -->
<div>
<h2>内容编辑</h2>
<table class="form-table">
<tr>
<th scope="row"><label for="ad_content">广告文案</label></th>
<td>
<textarea id="ad_content" name="ad_content" rows="4" class="large-text"></textarea>
<p class="description">广告的详细描述文案</p>
</td>
</tr>
<tr>
<th scope="row"><label for="button_text">按钮文字</label></th>
<td>
<input type="text" id="button_text" name="button_text" class="regular-text"
value="了解更多">
</td>
</tr>
<tr>
<th scope="row"><label for="custom_image">自定义图片</label></th>
<td>
<input type="text" id="custom_image" name="custom_image" class="regular-text"
placeholder="图片URL">
<button type="button" class="button" onclick="fagUploadImage()">
上传图片
</button>
</td>
</tr>
</table>
<h2>实时预览</h2>
<div id="ad-preview" style="border: 1px solid #ddd; padding: 20px; border-radius: 8px; min-height: 300px; background: #f9f9f9;">
<p style="text-align: center; color: #999;">选择广告类型和尺寸后,将显示预览</p>
</div>
<div style="margin-top: 20px; text-align: right;">
<button type="button" class="button" onclick="fagUpdatePreview()">
更新预览
</button>
<input type="submit" name="fag_create_ad" class="button button-primary" value="保存广告">
</div>
</div>
</div>
</form>
</div>
<script>
// 初始化尺寸选项
function fagUpdateDimensions() {
const adType = document.getElementById('ad_type').value;
const dimensionsSelect = document.getElementById('ad_dimensions');
// 清空现有选项
dimensionsSelect.innerHTML = '';
// 定义各类型的尺寸
const dimensions = {
'banner': ['728x90', '970x250', '320x100'],
'square': ['300x250', '250x250', '200x200'],
'vertical': ['300x600', '160x600']
};
if (dimensions[adType]) {
dimensions[adType].forEach(size => {
const option = document.createElement('option');
option.value = size;
option.textContent = size;
dimensionsSelect.appendChild(option);
});
}
// 更新预览
fagUpdatePreview();
}
// 生成AI内容
function fagGenerateContent() {
const keywords = document.getElementById('ai_keywords').value;
const tone = document.getElementById('tone_style').value;
if (!keywords) {
alert('请输入关键词');
return;
}
// 显示加载状态
const contentField = document.getElementById('ad_content');
contentField.value = 'AI正在生成文案...';
// 模拟AI生成(实际应使用AJAX调用服务器端)
setTimeout(() => {
const aiResponses = {
professional: `基于${keywords}的专业解决方案,提升您的业务效率。我们的专业团队为您提供卓越服务,确保最佳效果。`,
casual: `发现${keywords}的乐趣!轻松上手,简单操作,立即体验不一样的感受。`,
urgent: `限时优惠!${keywords}特别促销,机会难得,立即行动!`,
friendly: `您好!我们为您准备了${keywords}的特别服务,希望能给您带来愉快的体验。`
};
contentField.value = aiResponses[tone] || aiResponses.professional;
fagUpdatePreview();
}, 1000);
}
// 更新预览
function fagUpdatePreview() {
const previewDiv = document.getElementById('ad-preview');
const adType = document.getElementById('ad_type').value;
const dimensions = document.getElementById('ad_dimensions').value;
// 这里应该通过AJAX获取服务器端生成的预览
// 简化版:显示基本信息
previewDiv.innerHTML = `
<div style="text-align: center; padding: 20px;">
<h3>广告预览</h3>
<p><strong>类型:</strong>${adType}</p>
<p><strong>尺寸:</strong>${dimensions}</p>
<p><strong>标题:</strong>${document.getElementById('ad_title').value || '未设置'}</p>
<p><strong>文案:</strong>${document.getElementById('ad_content').value || '未设置'}</p>
<div style="margin-top: 20px; padding: 10px; background: #e0e0e0; border-radius: 4px;">
实际广告将根据设置动态生成
</div>
</div>
`;
}
// 初始化
document.addEventListener('DOMContentLoaded', function() {
fagUpdateDimensions();
});
</script>
<?php
}
/**
- 处理创建广告表单提交
*/
function fag_handle_create_ad($data) {
// 验证nonce
if (!wp_verify_nonce($data['fag_nonce'], 'fag_create_ad')) {
wp_die('安全验证失败');
}
global $wpdb;
$table_name = $wpdb->prefix . 'flexible_ads';
// 准备数据
$ad_data = array(
'title' => sanitize_text_field($data['ad_title']),
'ad_type' => sanitize_text_field($data['ad_type']),
'dimensions' => sanitize_text_field($data['ad_dimensions']),
'content' => wp_kses_post($data['ad_content']),
'target_url' => esc_url_raw($data['target_url']),
'button_text' => sanitize_text_field($data['button_text']),
'custom_image' => esc_url_raw($data['custom_image']),
'ai_keywords' => sanitize_text_field($data['ai_keywords']),
'tone_style' => sanitize_text_field($data['tone_style']),
'color_scheme' => sanitize_text_field($data['color_scheme'])
);
// 保存到数据库
$result = $wpdb->insert(
$table_name,
$ad_data
);
if ($result) {
echo '<div class="notice notice-success"><p>广告创建成功!</p></div>';
// 生成短代码
$ad_id = $wpdb->insert_id;
$shortcode = '[flexible_ad id="
