首页 / 教程文章 / 实现网络传媒柔性供应的WordPress插件开发教程

实现网络传媒柔性供应的WordPress插件开发教程

实现网络传媒柔性供应的WordPress插件开发教程

概述:什么是网络传媒柔性供应?

在当今快速变化的数字媒体环境中,网络传媒机构面临着内容需求波动大、资源分配不均的挑战。柔性供应系统通过动态调整内容生产、分发和资源分配,帮助传媒机构灵活应对市场需求变化。本教程将指导您开发一个WordPress插件,实现基本的柔性供应功能,包括内容自动调度、资源管理和多渠道发布。

开发环境准备

在开始开发之前,请确保您已准备好以下环境:

  1. WordPress 5.0+ 安装
  2. PHP 7.2+ 运行环境
  3. MySQL 5.6+ 数据库
  4. 代码编辑器(如VS Code、PHPStorm)
  5. 本地开发环境(如XAMPP、MAMP或Local by Flywheel)

插件基础结构搭建

首先,我们创建插件的基本目录结构和主文件:

<?php
/**
 * 插件名称: 网络传媒柔性供应系统
 * 插件URI: https://yourwebsite.com/
 * 描述: 实现网络传媒柔性供应的WordPress插件
 * 版本: 1.0.0
 * 作者: 您的名称
 * 作者URI: https://yourwebsite.com/
 * 许可证: GPL v2或更高版本
 * 文本域: flexible-media-supply
 */

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

// 定义插件常量
define('FMS_VERSION', '1.0.0');
define('FMS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FMS_PLUGIN_URL', plugin_dir_url(__FILE__));

// 初始化插件
class FlexibleMediaSupply {
    
    private static $instance = null;
    
    // 获取单例实例
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    // 构造函数
    private function __construct() {
        $this->init_hooks();
    }
    
    // 初始化钩子
    private function init_hooks() {
        // 激活/停用钩子
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
        
        // 管理菜单
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // 加载文本域
        add_action('init', array($this, 'load_textdomain'));
        
        // 初始化功能模块
        $this->init_modules();
    }
    
    // 激活插件
    public function activate() {
        // 创建数据库表
        $this->create_tables();
        
        // 设置默认选项
        $this->set_default_options();
        
        // 刷新重写规则
        flush_rewrite_rules();
    }
    
    // 停用插件
    public function deactivate() {
        // 清理临时数据
        // 注意:这里不删除数据,以便用户重新激活时保留设置
        flush_rewrite_rules();
    }
    
    // 加载文本域
    public function load_textdomain() {
        load_plugin_textdomain(
            'flexible-media-supply',
            false,
            dirname(plugin_basename(__FILE__)) . '/languages/'
        );
    }
    
    // 添加管理菜单
    public function add_admin_menu() {
        add_menu_page(
            __('柔性供应系统', 'flexible-media-supply'),
            __('柔性供应', 'flexible-media-supply'),
            'manage_options',
            'flexible-media-supply',
            array($this, 'render_dashboard'),
            'dashicons-schedule',
            30
        );
        
        // 添加子菜单
        add_submenu_page(
            'flexible-media-supply',
            __('内容调度', 'flexible-media-supply'),
            __('内容调度', 'flexible-media-supply'),
            'manage_options',
            'fms-content-schedule',
            array($this, 'render_content_schedule')
        );
        
        add_submenu_page(
            'flexible-media-supply',
            __('资源管理', 'flexible-media-supply'),
            __('资源管理', 'flexible-media-supply'),
            'manage_options',
            'fms-resource-management',
            array($this, 'render_resource_management')
        );
    }
    
    // 初始化模块
    private function init_modules() {
        // 这里将初始化各个功能模块
        require_once FMS_PLUGIN_DIR . 'includes/class-content-scheduler.php';
        require_once FMS_PLUGIN_DIR . 'includes/class-resource-manager.php';
        require_once FMS_PLUGIN_DIR . 'includes/class-multi-channel-publisher.php';
        
        // 初始化模块实例
        new Content_Scheduler();
        new Resource_Manager();
        new Multi_Channel_Publisher();
    }
    
    // 创建数据库表
    private function create_tables() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        // 内容调度表
        $table_name = $wpdb->prefix . 'fms_content_schedule';
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            schedule_time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            channel varchar(100) NOT NULL,
            status varchar(20) DEFAULT 'pending',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            KEY schedule_time (schedule_time)
        ) $charset_collate;";
        
        // 资源分配表
        $table_name2 = $wpdb->prefix . 'fms_resource_allocation';
        $sql2 = "CREATE TABLE IF NOT EXISTS $table_name2 (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            resource_type varchar(50) NOT NULL,
            resource_id bigint(20) NOT NULL,
            allocation_date date NOT NULL,
            hours_allocated decimal(5,2) DEFAULT 0.00,
            project_id bigint(20),
            notes text,
            PRIMARY KEY (id),
            KEY allocation_date (allocation_date),
            KEY resource_type (resource_type)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        dbDelta($sql2);
    }
    
    // 设置默认选项
    private function set_default_options() {
        $default_options = array(
            'auto_schedule' => true,
            'default_channels' => array('website', 'social_media'),
            'max_daily_posts' => 10,
            'resource_warning_threshold' => 80,
            'notification_email' => get_option('admin_email')
        );
        
        add_option('fms_settings', $default_options);
    }
    
    // 渲染仪表板
    public function render_dashboard() {
        ?>
        <div class="wrap">
            <h1><?php echo esc_html__('网络传媒柔性供应系统', 'flexible-media-supply'); ?></h1>
            <div class="fms-dashboard">
                <div class="fms-stats-container">
                    <div class="fms-stat-box">
                        <h3><?php echo esc_html__('今日计划内容', 'flexible-media-supply'); ?></h3>
                        <p class="stat-number"><?php echo $this->get_today_scheduled_count(); ?></p>
                    </div>
                    <div class="fms-stat-box">
                        <h3><?php echo esc_html__('可用资源', 'flexible-media-supply'); ?></h3>
                        <p class="stat-number"><?php echo $this->get_available_resources(); ?></p>
                    </div>
                    <div class="fms-stat-box">
                        <h3><?php echo esc_html__('多渠道发布', 'flexible-media-supply'); ?></h3>
                        <p class="stat-number"><?php echo $this->get_channel_count(); ?></p>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
    
    // 渲染内容调度页面
    public function render_content_schedule() {
        // 这里将实现内容调度界面
        echo '<div class="wrap"><h1>内容调度</h1></div>';
    }
    
    // 渲染资源管理页面
    public function render_resource_management() {
        // 这里将实现资源管理界面
        echo '<div class="wrap"><h1>资源管理</h1></div>';
    }
    
    // 获取今日计划内容数量
    private function get_today_scheduled_count() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'fms_content_schedule';
        $today = current_time('mysql');
        
        $count = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM $table_name WHERE DATE(schedule_time) = DATE(%s) AND status = 'pending'",
                $today
            )
        );
        
        return $count ? $count : 0;
    }
    
    // 获取可用资源
    private function get_available_resources() {
        // 简化示例,实际应计算实际可用资源
        return '85%';
    }
    
    // 获取渠道数量
    private function get_channel_count() {
        $settings = get_option('fms_settings', array());
        if (isset($settings['default_channels'])) {
            return count($settings['default_channels']);
        }
        return 0;
    }
}

// 初始化插件
FlexibleMediaSupply::get_instance();
?>

内容调度模块开发

内容调度是柔性供应系统的核心功能之一。以下是一个简化的内容调度类:

<?php
/**
 * 内容调度模块
 * 负责自动和手动安排内容发布时间
 */

class Content_Scheduler {
    
    public function __construct() {
        // 添加发布动作钩子
        add_action('save_post', array($this, 'schedule_on_save'), 10, 2);
        
        // 添加定时任务检查
        add_action('fms_check_scheduled_content', array($this, 'process_scheduled_content'));
        
        // 注册定时任务
        if (!wp_next_scheduled('fms_check_scheduled_content')) {
            wp_schedule_event(time(), 'hourly', 'fms_check_scheduled_content');
        }
        
        // 添加管理列
        add_filter('manage_post_posts_columns', array($this, 'add_schedule_column'));
        add_action('manage_post_posts_custom_column', array($this, 'render_schedule_column'), 10, 2);
    }
    
    /**
     * 保存文章时自动调度
     * @param int $post_id 文章ID
     * @param WP_Post $post 文章对象
     */
    public function schedule_on_save($post_id, $post) {
        // 检查自动发布权限
        if (!current_user_can('edit_post', $post_id) || wp_is_post_revision($post_id)) {
            return;
        }
        
        // 检查是否启用自动调度
        $settings = get_option('fms_settings', array());
        if (!isset($settings['auto_schedule']) || !$settings['auto_schedule']) {
            return;
        }
        
        // 获取文章类型
        $post_type = get_post_type($post_id);
        
        // 只处理文章和自定义类型
        if (!in_array($post_type, array('post', 'fms_content'))) {
            return;
        }
        
        // 检查是否已有调度
        $existing_schedule = $this->get_post_schedule($post_id);
        
        if (!$existing_schedule && $post->post_status == 'future') {
            // 如果文章是定时发布,创建调度记录
            $this->create_schedule($post_id, $post->post_date);
        }
    }
    
    /**
     * 创建内容调度
     * @param int $post_id 文章ID
     * @param string $schedule_time 调度时间
     * @param string $channel 发布渠道
     * @return bool 成功与否
     */
    public function create_schedule($post_id, $schedule_time, $channel = 'website') {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'fms_content_schedule';
        
        $result = $wpdb->insert(
            $table_name,
            array(
                'post_id' => $post_id,
                'schedule_time' => $schedule_time,
                'channel' => $channel,
                'status' => 'pending'
            ),
            array('%d', '%s', '%s', '%s')
        );
        
        return $result !== false;
    }
    
    /**
     * 处理已调度的内容
     */
    public function process_scheduled_content() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'fms_content_schedule';
        $current_time = current_time('mysql');
        
        // 获取到期的调度
        $scheduled_items = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM $table_name WHERE schedule_time <= %s AND status = 'pending'",
                $current_time
            )
        );
        
        foreach ($scheduled_items as $item) {
            // 发布内容
            $this->publish_content($item->post_id, $item->channel);
            
            // 更新状态
            $wpdb->update(
                $table_name,
                array('status' => 'published'),
                array('id' => $item->id),
                array('%s'),
                array('%d')
            );
        }
    }
    
    /**
     * 发布内容到指定渠道
     * @param int $post_id 文章ID
     * @param string $channel 发布渠道
     */
    private function publish_content($post_id, $channel) {
        $post = get_post($post_id);
        
        if (!$post) {
            return;
        }
        
        // 根据渠道执行不同的发布逻辑
        switch ($channel) {
            case 'website':
                // 更新文章状态为发布
                wp_publish_post($post_id);
                break;
                
            case 'social_media':
                // 发布到社交媒体(简化示例)
                $this->publish_to_social_media($post);
                break;
                
            // 可以添加更多渠道
        }
        
        // 记录发布日志
        $this->log_publication($post_id, $channel);
    }
    
    /**
     * 发布到社交媒体
     * @param WP_Post $post 文章对象
     */
    private function publish_to_social_media($post) {
        // 这里应集成社交媒体API
        // 简化示例:记录日志
        error_log('发布到社交媒体: ' . $post->post_title);
    }
    
    /**
     * 记录发布日志
     * @param int $post_id 文章ID
     * @param string $channel 发布渠道
     */
    private function log_publication($post_id, $channel) {
        // 这里可以记录详细的发布日志
        update_post_meta($post_id, '_fms_last_published', array(
            'channel' => $channel,
            'time' => current_time('mysql')
        ));
    }
    
    /**
     * 获取文章的调度信息
     * @param int $post_id 文章ID
     * @return object|null 调度信息
     */
    private function get_post_schedule($post_id) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'fms_content_schedule';
        
        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM $table_name WHERE post_id = %d AND status = 'pending'",
                $post_id
            )
        );
    }
    
    /**
     * 添加调度列到文章列表
     * @param array $columns 现有列
     * @return array 更新后的列
     */
    public function add_schedule_column($columns) {
        $columns['fms_schedule'] = __('调度状态', 'flexible-media-supply');
        return $columns;
    }
    
    /**
     * 渲染调度列内容
     * @param string $column 列名
     * @param int $post_id 文章ID
     */
    public function render_schedule_column($column, $post_id) {
        if ($column === 'fms_schedule') {
            $schedule = $this->get_post_schedule($post_id);
            
            if ($schedule) {
                echo '<span class="dashicons dashicons-clock" title="' 
                     . esc_attr(sprintf(__('计划于 %s 发布', 'flexible-media-supply'), $schedule->schedule_time)) 
                     . '"></span>';
            } else {
                echo '<span class="dashicons dashicons-minus" title="' 
                     . esc_attr__('未调度', 'flexible-media-supply') 
                     . '"></span>';
            }
        }
    }
}
?>

资源管理模块

资源管理是柔性供应系统的另一个关键组成部分:

<?php
/**
 * 资源管理模块
 * 管理人力、时间和内容资源
 */

class Resource_Manager {
    
    public function __construct() {
        // 添加资源管理页面
        add_action('admin_init', array($this, 'register_resource_settings'));
        
        // 添加上下文帮助
        add_action('load-toplevel_page_flexible-media-supply', array($this, 'add_help_tabs'));
        
        // 资源使用情况短代码
        add_shortcode('fms_resource_usage', array($this, 'resource_usage_shortcode'));
    }
    
    /**
     * 注册资源设置
     */
    public function register_resource_settings() {
        register_setting('fms_resource_settings', 'fms_resource_allocations');
        
        add_settings_section(
            'fms_resource_section',
            __('资源分配设置', 'flexible-media-supply'),
            array($this, 'render_resource_section'),
            'flexible-media-supply'
        );
        
        add_settings_field(
            'fms_editor_hours',
            __('编辑人员工时', 'flexible-media-supply'),

_field'),

        'flexible-media-supply',
        'fms_resource_section'
    );
    
    add_settings_field(
        'fms_designer_hours',
        __('设计人员工时', 'flexible-media-supply'),
        array($this, 'render_designer_hours_field'),
        'flexible-media-supply',
        'fms_resource_section'
    );
}

/**
 * 渲染资源部分说明
 */
public function render_resource_section() {
    echo '<p>' . __('配置您的团队资源分配,系统将根据这些设置优化内容生产计划。', 'flexible-media-supply') . '</p>';
}

/**
 * 渲染编辑工时字段
 */
public function render_editor_hours_field() {
    $allocations = get_option('fms_resource_allocations', array());
    $editor_hours = isset($allocations['editor_hours']) ? $allocations['editor_hours'] : 40;
    
    echo '<input type="number" name="fms_resource_allocations[editor_hours]" value="' . esc_attr($editor_hours) . '" min="0" max="168" />';
    echo '<p class="description">' . __('每周可用编辑工时(小时)', 'flexible-media-supply') . '</p>';
}

/**
 * 渲染设计工时字段
 */
public function render_designer_hours_field() {
    $allocations = get_option('fms_resource_allocations', array());
    $designer_hours = isset($allocations['designer_hours']) ? $allocations['designer_hours'] : 30;
    
    echo '<input type="number" name="fms_resource_allocations[designer_hours]" value="' . esc_attr($designer_hours) . '" min="0" max="168" />';
    echo '<p class="description">' . __('每周可用设计工时(小时)', 'flexible-media-supply') . '</p>';
}

/**
 * 计算资源使用率
 * @param string $resource_type 资源类型
 * @param string $period 时间周期
 * @return array 使用率数据
 */
public function calculate_resource_usage($resource_type = 'all', $period = 'week') {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'fms_resource_allocation';
    $allocations = get_option('fms_resource_allocations', array());
    
    // 计算时间范围
    $date_condition = '';
    if ($period === 'week') {
        $date_condition = "AND allocation_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
    } elseif ($period === 'month') {
        $date_condition = "AND allocation_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
    }
    
    // 查询已分配的资源
    $query = "SELECT resource_type, SUM(hours_allocated) as total_used 
              FROM $table_name 
              WHERE 1=1 $date_condition";
    
    if ($resource_type !== 'all') {
        $query .= $wpdb->prepare(" AND resource_type = %s", $resource_type);
    }
    
    $query .= " GROUP BY resource_type";
    
    $used_resources = $wpdb->get_results($query);
    
    // 计算使用率
    $usage_data = array();
    foreach ($used_resources as $resource) {
        $available_key = $resource->resource_type . '_hours';
        $available = isset($allocations[$available_key]) ? $allocations[$available_key] : 0;
        
        if ($available > 0) {
            $usage_percentage = ($resource->total_used / $available) * 100;
        } else {
            $usage_percentage = 0;
        }
        
        $usage_data[$resource->resource_type] = array(
            'used' => $resource->total_used,
            'available' => $available,
            'percentage' => round($usage_percentage, 2),
            'status' => $usage_percentage > 90 ? 'critical' : ($usage_percentage > 70 ? 'warning' : 'normal')
        );
    }
    
    return $usage_data;
}

/**
 * 分配资源到项目
 * @param string $resource_type 资源类型
 * @param int $resource_id 资源ID
 * @param float $hours 分配工时
 * @param string $date 分配日期
 * @param int $project_id 项目ID
 * @param string $notes 备注
 * @return bool 成功与否
 */
public function allocate_resource($resource_type, $resource_id, $hours, $date, $project_id = null, $notes = '') {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'fms_resource_allocation';
    
    // 检查是否超分配
    $usage_data = $this->calculate_resource_usage($resource_type, 'week');
    $allocations = get_option('fms_resource_allocations', array());
    $available_key = $resource_type . '_hours';
    $available = isset($allocations[$available_key]) ? $allocations[$available_key] : 0;
    
    $current_used = isset($usage_data[$resource_type]) ? $usage_data[$resource_type]['used'] : 0;
    
    if (($current_used + $hours) > $available) {
        // 记录警告但不阻止分配
        error_log(sprintf(
            __('资源分配警告:%s 类型资源分配超出可用量', 'flexible-media-supply'),
            $resource_type
        ));
    }
    
    $result = $wpdb->insert(
        $table_name,
        array(
            'resource_type' => $resource_type,
            'resource_id' => $resource_id,
            'allocation_date' => $date,
            'hours_allocated' => $hours,
            'project_id' => $project_id,
            'notes' => $notes
        ),
        array('%s', '%d', '%s', '%f', '%d', '%s')
    );
    
    return $result !== false;
}

/**
 * 资源使用情况短代码
 * @param array $atts 短代码属性
 * @return string 渲染的HTML
 */
public function resource_usage_shortcode($atts) {
    $atts = shortcode_atts(array(
        'type' => 'all',
        'period' => 'week',
        'show_chart' => 'true'
    ), $atts, 'fms_resource_usage');
    
    $usage_data = $this->calculate_resource_usage($atts['type'], $atts['period']);
    
    if (empty($usage_data)) {
        return '<p>' . __('暂无资源使用数据', 'flexible-media-supply') . '</p>';
    }
    
    ob_start();
    ?>
    <div class="fms-resource-usage">
        <h3><?php echo esc_html__('资源使用情况', 'flexible-media-supply'); ?></h3>
        <div class="resource-stats">
            <?php foreach ($usage_data as $type => $data): ?>
            <div class="resource-stat-item">
                <h4><?php echo esc_html($this->get_resource_type_label($type)); ?></h4>
                <div class="usage-bar">
                    <div class="usage-fill" style="width: <?php echo esc_attr(min($data['percentage'], 100)); ?>%; 
                        background-color: <?php echo $this->get_status_color($data['status']); ?>;">
                    </div>
                </div>
                <p class="usage-numbers">
                    <?php printf(
                        __('已用: %.1f / 可用: %.1f 小时 (%.1f%%)', 'flexible-media-supply'),
                        $data['used'],
                        $data['available'],
                        $data['percentage']
                    ); ?>
                </p>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <style>
        .fms-resource-usage { margin: 20px 0; }
        .resource-stat-item { margin-bottom: 15px; }
        .usage-bar { 
            height: 20px; 
            background: #f0f0f0; 
            border-radius: 10px; 
            overflow: hidden; 
            margin: 5px 0; 
        }
        .usage-fill { 
            height: 100%; 
            transition: width 0.5s ease; 
        }
        .usage-numbers { 
            font-size: 12px; 
            color: #666; 
            margin: 0; 
        }
    </style>
    <?php
    return ob_get_clean();
}

/**
 * 获取资源类型标签
 * @param string $type 资源类型
 * @return string 标签
 */
private function get_resource_type_label($type) {
    $labels = array(
        'editor' => __('编辑', 'flexible-media-supply'),
        'designer' => __('设计', 'flexible-media-supply'),
        'video' => __('视频制作', 'flexible-media-supply'),
        'seo' => __('SEO优化', 'flexible-media-supply')
    );
    
    return isset($labels[$type]) ? $labels[$type] : $type;
}

/**
 * 获取状态颜色
 * @param string $status 状态
 * @return string 颜色代码
 */
private function get_status_color($status) {
    $colors = array(
        'normal' => '#4CAF50',
        'warning' => '#FF9800',
        'critical' => '#F44336'
    );
    
    return isset($colors[$status]) ? $colors[$status] : '#4CAF50';
}

/**
 * 添加上下文帮助标签
 */
public function add_help_tabs() {
    $screen = get_current_screen();
    
    $screen->add_help_tab(array(
        'id' => 'fms_resource_help',
        'title' => __('资源管理', 'flexible-media-supply'),
        'content' => '<p>' . __('资源管理帮助内容...', 'flexible-media-supply') . '</p>'
    ));
}

}
?>


## 多渠道发布模块

<?php
/**

  • 多渠道发布模块
  • 管理内容分发到不同平台
    */

class Multi_Channel_Publisher {


private $channels = array();

public function __construct() {
    // 初始化可用渠道
    $this->init_channels();
    
    // 添加发布动作
    add_action('publish_post', array($this, 'on_post_publish'), 10, 2);
    
    // 添加上下文帮助
    add_action('load-post.php', array($this, 'add_channel_meta_box'));
    
    // 注册REST API端点
    add_action('rest_api_init', array($this, 'register_rest_routes'));
}

/**
 * 初始化渠道
 */
private function init_channels() {
    $this->channels = array(
        'website' => array(
            'name' => __('网站', 'flexible-media-supply'),
            'description' => __('发布到主网站', 'flexible-media-supply'),
            'enabled' => true,
            'auto_publish' => true
        ),
        'social_media' => array(
            'name' => __('社交媒体', 'flexible-media-supply'),
            'description' => __('发布到社交媒体平台', 'flexible-media-supply'),
            'enabled' => true,
            'auto_publish' => false
        ),
        'newsletter' => array(
            'name' => __('新闻邮件', 'flexible-media-supply'),
            'description' => __('包含在新闻邮件中', 'flexible-media-supply'),
            'enabled' => false,
            'auto_publish' => false
        ),
        'third_party' => array(
            'name' => __('第三方平台', 'flexible-media-supply'),
            'description' => __('分发到合作平台', 'flexible-media-supply'),
            'enabled' => false,
            'auto_publish' => false
        )
    );
    
    // 允许通过过滤器修改渠道
    $this->channels = apply_filters('fms_publishing_channels', $this->channels);
}

/**
 * 文章发布时触发多渠道发布
 * @param int $post_id 文章ID
 * @param WP_Post $post 文章对象
 */
public function on_post_publish($post_id, $post) {
    // 检查是否自动发布到其他渠道
    $auto_channels = $this->get_auto_publish_channels();
    
    foreach ($auto_channels as $channel_id => $channel) {
        if ($channel['enabled'] && $channel['auto_publish']) {
            $this->publish_to_channel($post_id, $channel_id);
        }
    }
}

/**
 * 发布到指定渠道
 * @param int $post_id 文章ID
 * @param string $channel_id 渠道ID
 * @return bool 成功与否
 */
public function publish_to_channel($post_id, $channel_id) {
    if (!isset($this->channels[$channel_id]) || !$this->channels[$channel_id]['enabled']) {
        return false;
    }
    
    $post = get_post($post_id);
    if (!$post) {
        return false;
    }
    
    // 根据渠道执行不同的发布逻辑
    switch ($channel_id) {
        case 'website':
            // 网站发布已在WordPress中处理
            $result = true;
            break;
            
        case 'social_media':
            $result = $this->publish_to_social_media($post);
            break;
            
        case 'newsletter':
            $result = $this->add_to_newsletter($post);
            break;
            
        case 'third_party':
            $result = $this->publish_to_third_party($post);
            break;
            
        default:
            // 允许通过钩子添加自定义渠道
            $result = apply_filters('fms_publish_to_channel', false, $post, $channel_id);
            break;
    }
    
    // 记录发布状态
    if ($result) {
        $this->log_channel_publication($post_id, $channel_id, 'success');
    } else {
        $this->log_channel_publication($post_id, $channel_id, 'failed');
    }
    
    return $result;
}

/**
 * 发布到社交媒体
 * @param WP_Post $post 文章对象
 * @return bool 成功与否
 */
private function publish_to_social_media($post) {
    // 这里应集成社交媒体API
    // 简化示例:模拟API调用
    
    $message = $this->prepare_social_media_message($post);
    
    // 模拟发布到不同平台
    $platforms = array('twitter', 'facebook', 'linkedin');
    $success_count = 0;
    
    foreach ($platforms as $platform) {
        // 这里应该是实际的API调用
        // $api_result = $this->call_social_media_api($platform, $message);
        $api_result = true; // 模拟成功
        
        if ($api_result) {
            $success_count++;
            $this->log_social_media_post($post->ID, $platform, $message);
        }
    }
    
    return $success_count > 0;
}

/**
 * 准备社交媒体消息
 * @param WP_Post $post 文章对象
 * @return string 格式化消息
 */
private function prepare_social_media_message($post) {
    $title = wp_strip_all_tags($post->post_title);
    $excerpt = wp_trim_words(wp_strip_all_tags($post->post_excerpt), 20);
    $url = get_permalink($post->ID);
    
    // 根据不同平台调整消息格式
    $message = sprintf(
        __('新文章发布: %s - %s %s', 'flexible-media-supply'),
        $title,
        $excerpt,
        $url
    );
    
    // 限制长度(针对Twitter等平台)
    if (strlen($message) > 280) {
        $message = substr($message, 0, 277) . '...';
    }
    
    return $message;
}

/**
 * 添加到新闻邮件
 * @param WP_Post $post 文章对象
 * @return bool 成功与否
 */
private function add_to_newsletter($post) {
    // 这里应集成邮件服务
    // 简化示例:添加到待发送队列
    
    $newsletter_queue = get_option('fms_newsletter_queue', array());
    
    $newsletter_queue[] = array(
        'post_id' => $post->ID,
        'added_time' => current_time('mysql'),
        'status' => 'pending'
    );
    
    update_option('fms_newsletter_queue', $newsletter_queue);
    
    return true;
}

/**
 * 发布到第三方平台
 * @param WP_Post $post 文章对象
 * @return bool 成功与否
 */
private function publish_to_third_party($post) {
    // 这里应集成第三方平台API
    // 简化示例:记录日志
    
    error_log(sprintf(
        __('文章 "%s" 已排队等待发布到第三方平台', 'flexible-media-supply'),
        $post->post_title
    ));
    
    return true;
}

/**
 * 记录社交媒体发布
 * @param int $post_id 文章ID
 * @param string $platform 平台名称
 * @param string $message 发布消息
 */
private function log_social_media_post($post_id, $platform, $message) {
    $social_logs = get_post_meta($post_id, '_fms_social_media_logs', true);
    if (!is_array($social_logs)) {
        $social_logs = array();
    }
    
    $social_logs[] = array(
        'platform' => $platform,
        'message' => $message,
        'time' => current
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5653.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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