首页 / 教程文章 / 网络传媒WordPress多平台柔性分发系统构建教程

网络传媒WordPress多平台柔性分发系统构建教程

网络传媒WordPress多平台柔性分发系统构建教程

概述:多平台内容分发的挑战与机遇

在当今数字化媒体环境中,网络传媒机构面临着内容多平台分发的巨大挑战。每个社交平台、新闻聚合器和内容社区都有其独特的内容格式、API接口和用户偏好。手动将WordPress网站内容同步到各个平台不仅耗时耗力,还容易出错。本教程将指导您构建一个柔性分发系统,实现WordPress内容到多个平台的智能自动化分发。

柔性分发系统的核心优势在于其适应性和可扩展性——当新的平台出现或现有平台API变更时,您可以快速调整系统而无需重构整个架构。

系统架构设计

我们的柔性分发系统将采用模块化设计,包含以下核心组件:

  1. 内容监听器:监测WordPress内容变化
  2. 内容处理器:格式化内容以适应不同平台
  3. 平台适配器:处理各平台API交互
  4. 分发调度器:管理分发队列和优先级
  5. 状态追踪器:监控分发状态和结果
<?php
/**
 * WordPress多平台柔性分发系统 - 主架构类
 */
class MultiPlatformDistributionSystem {
    
    private $platform_adapters = array();
    private $content_processor;
    private $distribution_scheduler;
    
    /**
     * 初始化分发系统
     */
    public function __construct() {
        $this->content_processor = new ContentProcessor();
        $this->distribution_scheduler = new DistributionScheduler();
        $this->register_default_hooks();
    }
    
    /**
     * 注册WordPress钩子
     */
    private function register_default_hooks() {
        // 监听文章发布或更新
        add_action('save_post', array($this, 'handle_post_save'), 10, 3);
        
        // 监听文章状态变化
        add_action('transition_post_status', array($this, 'handle_status_change'), 10, 3);
    }
    
    /**
     * 注册平台适配器
     * @param string $platform_name 平台名称
     * @param object $adapter 适配器实例
     */
    public function register_platform_adapter($platform_name, $adapter) {
        $this->platform_adapters[$platform_name] = $adapter;
        error_log("平台适配器已注册: " . $platform_name);
    }
    
    /**
     * 处理文章保存事件
     */
    public function handle_post_save($post_id, $post, $update) {
        // 只处理已发布文章
        if ($post->post_status !== 'publish' || $post->post_type !== 'post') {
            return;
        }
        
        // 检查是否已分发过
        if (get_post_meta($post_id, '_distributed', true)) {
            return;
        }
        
        $this->process_and_distribute($post);
    }
    
    /**
     * 处理和分发内容
     */
    private function process_and_distribute($post) {
        // 处理内容
        $processed_content = $this->content_processor->process($post);
        
        // 添加到分发队列
        $this->distribution_scheduler->add_to_queue($post->ID, $processed_content);
        
        error_log("文章已加入分发队列: " . $post->ID);
    }
}
?>

内容监听器实现

内容监听器负责监测WordPress内容变化,并触发分发流程。以下是完整实现:

<?php
/**
 * 内容监听器类
 * 监控WordPress内容变化并触发相应动作
 */
class ContentListener {
    
    /**
     * 初始化监听器
     */
    public function init() {
        // 文章发布时触发
        add_action('publish_post', array($this, 'on_post_publish'), 10, 2);
        
        // 文章更新时触发
        add_action('post_updated', array($this, 'on_post_update'), 10, 3);
        
        // 定时检查待分发内容
        add_action('mpds_daily_distribution_check', array($this, 'check_scheduled_distribution'));
    }
    
    /**
     * 处理文章发布事件
     * @param int $post_id 文章ID
     * @param WP_Post $post 文章对象
     */
    public function on_post_publish($post_id, $post) {
        // 验证文章类型和状态
        if ($this->should_distribute($post)) {
            $this->trigger_distribution($post_id, 'publish');
        }
    }
    
    /**
     * 处理文章更新事件
     */
    public function on_post_update($post_id, $post_after, $post_before) {
        // 只有当文章状态变为发布时才分发
        if ($post_after->post_status === 'publish' && 
            $post_before->post_status !== 'publish') {
            if ($this->should_distribute($post_after)) {
                $this->trigger_distribution($post_id, 'update');
            }
        }
    }
    
    /**
     * 判断是否应该分发
     */
    private function should_distribute($post) {
        // 检查文章类型
        if ($post->post_type !== 'post') {
            return false;
        }
        
        // 检查是否已分发
        $already_distributed = get_post_meta($post->ID, '_mpds_distributed', true);
        if ($already_distributed) {
            return false;
        }
        
        // 检查是否有排除分类
        $excluded_categories = get_option('mpds_excluded_categories', array());
        $post_categories = wp_get_post_categories($post->ID);
        
        foreach ($post_categories as $cat_id) {
            if (in_array($cat_id, $excluded_categories)) {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * 触发分发流程
     */
    private function trigger_distribution($post_id, $trigger_type) {
        // 记录分发时间
        update_post_meta($post_id, '_mpds_distribution_trigger', $trigger_type);
        update_post_meta($post_id, '_mpds_distribution_time', current_time('mysql'));
        
        // 触发分发动作
        do_action('mpds_distribute_content', $post_id);
        
        error_log("分发已触发: 文章ID " . $post_id . ", 触发类型: " . $trigger_type);
    }
}
?>

内容处理器与平台适配器

内容处理器负责将WordPress内容转换为适合不同平台的格式:

<?php
/**
 * 内容处理器类
 * 将WordPress内容转换为适合不同平台的格式
 */
class ContentProcessor {
    
    /**
     * 处理文章内容
     * @param WP_Post $post WordPress文章对象
     * @return array 处理后的内容数组
     */
    public function process($post) {
        $processed = array(
            'id' => $post->ID,
            'title' => $this->process_title($post->post_title),
            'content' => $this->process_content($post->post_content),
            'excerpt' => $this->process_excerpt($post),
            'images' => $this->extract_images($post->ID),
            'tags' => $this->extract_tags($post->ID),
            'categories' => $this->extract_categories($post->ID),
            'url' => get_permalink($post->ID),
            'author' => get_the_author_meta('display_name', $post->post_author),
            'publish_date' => $post->post_date
        );
        
        return $processed;
    }
    
    /**
     * 处理标题 - 移除HTML标签,限制长度
     */
    private function process_title($title) {
        $title = wp_strip_all_tags($title);
        
        // 不同平台标题长度限制
        $platform_limits = array(
            'twitter' => 280,
            'facebook' => 100,
            'linkedin' => 200,
            'default' => 120
        );
        
        return $title;
    }
    
    /**
     * 处理内容 - 清理HTML,提取纯文本
     */
    private function process_content($content) {
        // 移除所有HTML标签
        $plain_text = wp_strip_all_tags($content);
        
        // 移除短代码
        $plain_text = strip_shortcodes($plain_text);
        
        // 标准化空格和换行
        $plain_text = preg_replace('/s+/', ' ', $plain_text);
        
        return trim($plain_text);
    }
    
    /**
     * 提取文章中的图片
     */
    private function extract_images($post_id) {
        $images = array();
        
        // 获取文章特色图片
        $featured_image_id = get_post_thumbnail_id($post_id);
        if ($featured_image_id) {
            $featured_image = wp_get_attachment_image_src($featured_image_id, 'full');
            if ($featured_image) {
                $images['featured'] = $featured_image[0];
            }
        }
        
        // 从内容中提取图片
        $content = get_post_field('post_content', $post_id);
        preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $content, $matches);
        
        if (!empty($matches[1])) {
            $images['content'] = $matches[1];
        }
        
        return $images;
    }
}

/**
 * 平台适配器抽象类
 * 所有平台适配器的基类
 */
abstract class PlatformAdapter {
    
    protected $platform_name;
    protected $api_key;
    protected $api_secret;
    protected $access_token;
    
    /**
     * 初始化适配器
     */
    public function __construct($config) {
        $this->api_key = $config['api_key'] ?? '';
        $this->api_secret = $config['api_secret'] ?? '';
        $this->access_token = $config['access_token'] ?? '';
        $this->initialize();
    }
    
    /**
     * 初始化方法,子类可覆盖
     */
    protected function initialize() {
        // 平台特定的初始化逻辑
    }
    
    /**
     * 分发内容到平台
     * @param array $content 处理后的内容
     * @return array 分发结果
     */
    abstract public function distribute($content);
    
    /**
     * 测试API连接
     * @return bool 连接是否成功
     */
    abstract public function test_connection();
    
    /**
     * 获取平台名称
     */
    public function get_platform_name() {
        return $this->platform_name;
    }
}

/**
 * 微博平台适配器示例
 */
class WeiboAdapter extends PlatformAdapter {
    
    protected $platform_name = 'weibo';
    
    /**
     * 分发内容到微博
     */
    public function distribute($content) {
        // 微博API端点
        $api_url = 'https://api.weibo.com/2/statuses/share.json';
        
        // 准备微博内容(限制140字)
        $weibo_content = $this->format_for_weibo($content);
        
        // 准备API请求参数
        $params = array(
            'access_token' => $this->access_token,
            'status' => $weibo_content
        );
        
        // 如果有图片,先上传图片
        if (!empty($content['images'])) {
            $picture_url = $this->upload_picture($content['images'][0]);
            if ($picture_url) {
                $params['pic'] = $picture_url;
            }
        }
        
        // 发送请求
        $response = wp_remote_post($api_url, array(
            'body' => $params,
            'timeout' => 30
        ));
        
        // 处理响应
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message(),
                'platform' => $this->platform_name
            );
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['error_code'])) {
            return array(
                'success' => false,
                'message' => $body['error'],
                'platform' => $this->platform_name
            );
        }
        
        return array(
            'success' => true,
            'message' => '内容已成功发布到微博',
            'platform' => $this->platform_name,
            'post_id' => $body['id'] ?? '',
            'url' => $body['url'] ?? ''
        );
    }
    
    /**
     * 格式化内容以适应微博
     */
    private function format_for_weibo($content) {
        $text = $content['title'] . ' ' . $content['excerpt'];
        
        // 微博字数限制
        if (mb_strlen($text, 'UTF-8') > 140) {
            $text = mb_substr($text, 0, 137, 'UTF-8') . '...';
        }
        
        // 添加原文链接
        $text .= ' ' . $content['url'];
        
        return $text;
    }
    
    /**
     * 上传图片到微博
     */
    private function upload_picture($image_url) {
        // 实现图片上传逻辑
        // 这里简化处理,实际需要调用微博图片上传API
        return $image_url;
    }
    
    /**
     * 测试微博API连接
     */
    public function test_connection() {
        $test_url = 'https://api.weibo.com/2/account/get_uid.json';
        
        $response = wp_remote_get($test_url . '?access_token=' . $this->access_token);
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        return isset($body['uid']);
    }
}
?>

分发调度器与状态追踪

<?php
/**
 * 分发调度器类
 * 管理分发队列和优先级
 */
class DistributionScheduler {
    
    private $queue_table;
    
    /**
     * 初始化调度器
     */
    public function __construct() {
        global $wpdb;
        $this->queue_table = $wpdb->prefix . 'mpds_distribution_queue';
        
        // 创建队列表(如果不存在)
        $this->create_queue_table();
        
        // 设置定时任务处理队列
        add_action('mpds_process_distribution_queue', array($this, 'process_queue'));
        
        if (!wp_next_scheduled('mpds_process_distribution_queue')) {
            wp_schedule_event(time(), 'every_5_minutes', 'mpds_process_distribution_queue');
        }
    }
    
    /**
     * 创建分发队列表
     */
    private function create_queue_table() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS {$this->queue_table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            content longtext NOT NULL,
            platforms text NOT NULL,
            status varchar(20) DEFAULT 'pending',
            attempts int(11) DEFAULT 0,
            last_attempt datetime DEFAULT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            scheduled_for datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            KEY status (status),
            KEY scheduled_for (scheduled_for)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * 添加到分发队列
     */
    public function add_to_queue($post_id, $content, $platforms = null) {
        global $wpdb;
        
        // 如果未指定平台,使用所有已启用的平台
        if ($platforms === null) {
            $platforms = $this->get_enabled_platforms();
        }
        
        // 序列化平台列表
        $platforms_serialized = maybe_serialize($platforms);
        
        // 插入队列记录
        $wpdb->insert(
            $this->queue_table,
            array(
                'post_id' => $post_id,
                'content' => maybe_serialize($content),
                'platforms' => $platforms_serialized,
                'status' => 'pending',
                'scheduled_for' => current_time('mysql')
            ),
            array('%d', '%s', '%s', '%s', '%s')
        );
        
        return $wpdb->insert_id;
    }
    
    /**
     * 处理分发队列
     */
    public function process_queue() {
        global $wpdb;
        
        // 获取待处理的任务(限制每次处理5个)
        $pending_items = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$this->queue_table} 
                WHERE status = 'pending' 
                AND scheduled_for <= %s 
                AND attempts < 3 
                ORDER BY scheduled_for ASC 
                LIMIT 5",
                current_time('mysql')
            )
        );
        
        foreach ($pending_items as $item) {
            $this->process_queue_item($item);
        }
    }
    
    /**
     * 处理单个队列项目
     */
    private function process_queue_item($item) {
        global $wpdb;
        
        // 更新状态为处理中
        $wpdb->update(
            $this->queue_table,
            array(
                'status' => 'processing',
                'last_attempt' => current_time('mysql'),
                'attempts' => $item->attempts + 1
            ),
            array('id' => $item->id),
            array('%s', '%s', '%d'),
            array('%d')
        );
        
        // 反序列化内容
        $content = maybe_unserialize($item->content);
        $platforms = maybe_unserialize($item->platforms);
        
        // 分发到各个平台
        $results = array();
        foreach ($platforms as $platform_name) {
            $adapter = $this->get_platform_adapter($platform_name);
            if ($adapter) {
                $result = $adapter->distribute($content);
                $results[$platform_name] = $result;
                
                // 记录分发结果

ribution_result($item->post_id, $platform_name, $result);

        }
    }
    
    // 更新队列状态
    $all_success = true;
    foreach ($results as $result) {
        if (!$result['success']) {
            $all_success = false;
            break;
        }
    }
    
    $new_status = $all_success ? 'completed' : 'failed';
    $wpdb->update(
        $this->queue_table,
        array('status' => $new_status),
        array('id' => $item->id),
        array('%s'),
        array('%d')
    );
    
    // 如果分发成功,标记文章为已分发
    if ($all_success) {
        update_post_meta($item->post_id, '_mpds_distributed', true);
        update_post_meta($item->post_id, '_mpds_distribution_time', current_time('mysql'));
    }
    
    return $results;
}

/**
 * 记录分发结果
 */
private function record_distribution_result($post_id, $platform, $result) {
    $results = get_post_meta($post_id, '_mpds_distribution_results', true);
    if (!is_array($results)) {
        $results = array();
    }
    
    $results[$platform] = array(
        'success' => $result['success'],
        'message' => $result['message'],
        'time' => current_time('mysql'),
        'platform_post_id' => $result['post_id'] ?? '',
        'url' => $result['url'] ?? ''
    );
    
    update_post_meta($post_id, '_mpds_distribution_results', $results);
}

/**
 * 获取已启用的平台列表
 */
private function get_enabled_platforms() {
    $enabled_platforms = get_option('mpds_enabled_platforms', array());
    return is_array($enabled_platforms) ? $enabled_platforms : array();
}

/**
 * 获取平台适配器实例
 */
private function get_platform_adapter($platform_name) {
    // 这里应该从适配器管理器获取实例
    // 简化实现,实际应用中应有更完整的适配器管理
    $adapters = apply_filters('mpds_platform_adapters', array());
    return $adapters[$platform_name] ?? null;
}

}

/**

  • 状态追踪器类
  • 监控分发状态和结果
    */

class StatusTracker {


/**
 * 初始化追踪器
 */
public function init() {
    add_action('admin_menu', array($this, 'add_admin_menu'));
    add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
}

/**
 * 添加管理菜单
 */
public function add_admin_menu() {
    add_menu_page(
        '多平台分发',
        '内容分发',
        'manage_options',
        'mpds-dashboard',
        array($this, 'render_dashboard'),
        'dashicons-share',
        30
    );
    
    add_submenu_page(
        'mpds-dashboard',
        '分发状态',
        '分发状态',
        'manage_options',
        'mpds-status',
        array($this, 'render_status_page')
    );
    
    add_submenu_page(
        'mpds-dashboard',
        '平台设置',
        '平台设置',
        'manage_options',
        'mpds-platforms',
        array($this, 'render_platforms_page')
    );
}

/**
 * 渲染仪表板
 */
public function render_dashboard() {
    global $wpdb;
    
    // 获取统计数据
    $queue_table = $wpdb->prefix . 'mpds_distribution_queue';
    
    $stats = array(
        'total' => $wpdb->get_var("SELECT COUNT(*) FROM {$queue_table}"),
        'pending' => $wpdb->get_var("SELECT COUNT(*) FROM {$queue_table} WHERE status = 'pending'"),
        'completed' => $wpdb->get_var("SELECT COUNT(*) FROM {$queue_table} WHERE status = 'completed'"),
        'failed' => $wpdb->get_var("SELECT COUNT(*) FROM {$queue_table} WHERE status = 'failed'")
    );
    
    // 获取最近的分发记录
    $recent_distributions = $wpdb->get_results(
        "SELECT q.*, p.post_title 
         FROM {$queue_table} q 
         LEFT JOIN {$wpdb->posts} p ON q.post_id = p.ID 
         ORDER BY q.created_at DESC 
         LIMIT 10"
    );
    
    ?>
    <div class="wrap mpds-dashboard">
        <h1>多平台分发系统仪表板</h1>
        
        <div class="mpds-stats-container">
            <div class="mpds-stat-card">
                <h3>总任务数</h3>
                <p class="stat-number"><?php echo esc_html($stats['total']); ?></p>
            </div>
            <div class="mpds-stat-card">
                <h3>待处理</h3>
                <p class="stat-number"><?php echo esc_html($stats['pending']); ?></p>
            </div>
            <div class="mpds-stat-card">
                <h3>已完成</h3>
                <p class="stat-number"><?php echo esc_html($stats['completed']); ?></p>
            </div>
            <div class="mpds-stat-card">
                <h3>失败</h3>
                <p class="stat-number"><?php echo esc_html($stats['failed']); ?></p>
            </div>
        </div>
        
        <h2>最近分发记录</h2>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>文章标题</th>
                    <th>状态</th>
                    <th>尝试次数</th>
                    <th>创建时间</th>
                    <th>最后尝试</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recent_distributions as $dist): ?>
                <tr>
                    <td>
                        <a href="<?php echo get_edit_post_link($dist->post_id); ?>">
                            <?php echo esc_html($dist->post_title ?: '文章ID: ' . $dist->post_id); ?>
                        </a>
                    </td>
                    <td>
                        <span class="status-badge status-<?php echo esc_attr($dist->status); ?>">
                            <?php echo esc_html($this->get_status_label($dist->status)); ?>
                        </span>
                    </td>
                    <td><?php echo esc_html($dist->attempts); ?></td>
                    <td><?php echo esc_html($dist->created_at); ?></td>
                    <td><?php echo esc_html($dist->last_attempt ?: '从未尝试'); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <style>
    .mpds-stats-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin: 20px 0;
    }
    .mpds-stat-card {
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        text-align: center;
    }
    .mpds-stat-card h3 {
        margin: 0 0 10px 0;
        color: #666;
        font-size: 14px;
        text-transform: uppercase;
    }
    .mpds-stat-card .stat-number {
        font-size: 32px;
        font-weight: bold;
        margin: 0;
        color: #2271b1;
    }
    .status-badge {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
    }
    .status-pending { background: #f0ad4e; color: white; }
    .status-processing { background: #5bc0de; color: white; }
    .status-completed { background: #5cb85c; color: white; }
    .status-failed { background: #d9534f; color: white; }
    </style>
    <?php
}

/**
 * 获取状态标签
 */
private function get_status_label($status) {
    $labels = array(
        'pending' => '待处理',
        'processing' => '处理中',
        'completed' => '已完成',
        'failed' => '失败'
    );
    return $labels[$status] ?? $status;
}

/**
 * 渲染状态页面
 */
public function render_status_page() {
    // 实现状态页面
    echo '<div class="wrap"><h1>分发状态详情</h1></div>';
}

/**
 * 渲染平台设置页面
 */
public function render_platforms_page() {
    // 实现平台设置页面
    echo '<div class="wrap"><h1>平台设置</h1></div>';
}

/**
 * 加载管理端脚本和样式
 */
public function enqueue_admin_scripts($hook) {
    if (strpos($hook, 'mpds-') === false) {
        return;
    }
    
    wp_enqueue_style(
        'mpds-admin-style',
        plugins_url('css/mpds-admin.css', __FILE__)
    );
    
    wp_enqueue_script(
        'mpds-admin-script',
        plugins_url('js/mpds-admin.js', __FILE__),
        array('jquery'),
        '1.0.0',
        true
    );
}

}
?>


## 系统集成与部署

### 1. 主插件文件

<?php
/**

  • Plugin Name: 网络传媒多平台柔性分发系统
  • Plugin URI: https://yourwebsite.com/
  • Description: WordPress内容多平台自动化分发系统
  • Version: 1.0.0
  • Author: 网络传媒
  • License: GPL v2 or later
    */

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

exit;

}

// 定义插件常量
define('MPDS_VERSION', '1.0.0');
define('MPDS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('MPDS_PLUGIN_URL', plugin_dir_url(__FILE__));

// 自动加载类文件
spl_autoload_register(function ($class_name) {

$class_map = array(
    'MultiPlatformDistributionSystem' => 'includes/class-mpds-system.php',
    'ContentListener' => 'includes/class-content-listener.php',
    'ContentProcessor' => 'includes/class-content-processor.php',
    'PlatformAdapter' => 'includes/abstracts/class-platform-adapter.php',
    'WeiboAdapter' => 'includes/adapters/class-weibo-adapter.php',
    'WeChatAdapter' => 'includes/adapters/class-wechat-adapter.php',
    'DistributionScheduler' => 'includes/class-distribution-scheduler.php',
    'StatusTracker' => 'includes/class-status-tracker.php',
);

if (isset($class_map[$class_name])) {
    require_once MPDS_PLUGIN_DIR . $class_map[$class_name];
}

});

// 初始化系统
function mpds_init() {

// 检查必要扩展
if (!extension_loaded('curl')) {
    add_action('admin_notices', function() {
        echo '<div class="notice notice-error"><p>多平台分发系统需要cURL扩展支持。</p></div>';
    });
    return;
}

// 初始化核心组件
$system = new MultiPlatformDistributionSystem();
$listener = new ContentListener();
$scheduler = new DistributionScheduler();
$tracker = new StatusTracker();

// 注册平台适配器
$platforms_config = get_option('mpds_platforms_config', array());

foreach ($platforms_config as $platform => $config) {
    if ($config['enabled']) {
        $adapter_class = 'MPDS_' . ucfirst($platform) . 'Adapter';
        if (class_exists($adapter_class)) {
            $adapter = new $adapter_class($config);
            $system->register_platform_adapter($platform, $adapter);
        }
    }
}

// 初始化追踪器
$tracker->init();

// 注册激活/停用钩子
register_activation_hook(__FILE__, 'mpds_activate');
register_deactivation_hook(__FILE__, 'mpds_deactivate');

}
add_action('plugins_loaded', 'mpds_init');

// 插件激活时执行
function mpds_activate() {

// 创建数据库表
global $wpdb;

$charset_collate = $wpdb->get_charset_collate();

// 分发队列表
$queue_table = $wpdb->prefix . 'mpds_distribution_queue';
$sql = "CREATE TABLE IF NOT EXISTS $queue_table (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    post_id bigint(20) NOT NULL,
    content longtext NOT NULL,
    platforms text NOT NULL,
    status varchar(20) DEFAULT 'pending',
    attempts int(11) DEFAULT 0,
    last_attempt datetime DEFAULT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    scheduled_for datetime DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY post_id (post_id),
    KEY status (status),
    KEY scheduled_for (scheduled_for)
) $charset_collate;";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);

// 分发日志表
$logs_table = $wpdb->prefix . 'mpds_distribution_logs';
$sql = "CREATE TABLE IF NOT EXISTS $logs_table (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    post_id bigint(20) NOT NULL,
    platform varchar(50) NOT NULL,
    success tinyint(1) DEFAULT 0,
    message text,
    response_data longtext,
    distributed_at datetime DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY post_id (post_id),
    KEY platform (platform),
    KEY distributed_at (distributed_at)
) $charset_collate;";

dbDelta($sql);

// 设置默认选项
add_option('mpds_version', MPDS_VERSION);
add_option('mpds_enabled_platforms', array('weibo', 'wechat'));
add_option('mpds_default_distribution_delay', 0);
add_option('mpds_max_retry_attempts', 3);

// 添加自定义定时任务间隔
add_filter('cron_schedules', function($schedules) {
    $schedules['every_5_minutes'] = array(
        'interval' => 300,
        'display' => __('每5分钟')
    );
    return $schedules;
});

}

// 插件停用时执行
function mpds_deactivate() {

// 清理定时任务
wp_clear_scheduled_hook('mpds_process_distribution_queue');
wp_clear_scheduled_hook('mpds_daily_distribution_check');

}

// 添加设置链接
add_filter('plugin_action_links_' . plugin_basename(__FILE__), function($links) {

$settings_link = '<a href="admin.php?page=mpds-dashboard">' . __('设置') . '</a>';
array_unshift($links, $settings_link);
return $links;

});
?>


## 配置与使用指南

### 1. 系统配置

在WordPress后台完成以下配置:

1. **平台配置**:进入"内容分发 → 平台设置",配置各平台的API密钥和访问令牌
2. **分发规则**:设置内容过滤规则、分发时间延迟和重试策略
3. **内容映射**:配置不同平台的内容格式转换规则

### 2. 扩展新平台

要添加新的分发平台,只需创建新的适配器类:

<?php
/**

  • 抖音平台适配器示例
    */

class DouyinAdapter extends PlatformAdapter {


protected $platform_name = 'douyin';

public function distribute($content) {
    // 实现抖音API调用逻辑
    // 注意抖音的视频内容特殊处理
    
    $video_url = $this->process_video_content($content);
    
    // 调用抖音发布API
    $result = $this->call_douyin_api('/video/upload', array(
        'video_url' => $video_url,
        'description' => $this->format_description($content)
    ));
    
    return $result;
}

private function process_video_content($content) {
    // 提取或转换视频内容
    // 实际实现需要根据抖音API要求处理
    return $content['video_url'] ?? '';
}

public function test_connection() {
    // 测试抖音API连接
    return true;
}

}
?>


### 3. 监控与维护

系统提供完整的监控功能:

1. **实时状态监控**:查看分发队列状态和成功率
2. **错误日志**:详细记录分发失败的原因和上下文
3. **性能统计**:监控API调用响应时间和成功率
4. **内容分析**:分析各平台的内容表现和互动数据

## 总结

本文详细介绍了构建WordPress多平台柔性分发系统的完整方案。该系统具有以下特点:

1. **模块化设计**:各组件职责明确,易于维护和扩展
2. **平台无关性**:通过适配器模式支持任意内容平台
3. **容错机制**:完善的错误处理和重试逻辑
4. **实时监控**:全面的状态追踪和性能监控
5. **配置灵活**:支持多种分发规则和内容转换策略

通过本系统,网络传媒机构可以大幅提升内容分发效率,确保内容在不同平台保持一致的品牌形象,同时根据各平台特点进行优化调整。系统的柔性设计确保了长期可维护性和技术债务的可控性。
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5722.html

EXCHANGES®作者

EXCHANGES® 技术支持:漳州柔性供应链服务有限公司
上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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