文章目录[隐藏]
手把手教程:实现网站内容的多平台一键分发与推广,通过WordPress程序的代码二次开发实现常用互联网小工具功能
引言:内容分发的挑战与机遇
在当今数字时代,内容创作者和网站管理员面临着一个共同的挑战:如何高效地将优质内容分发到多个平台,同时保持品牌一致性和用户参与度。每天,数以百万计的文章、视频和图片在互联网上发布,但只有少数能够真正触达目标受众。传统的内容分发方式需要手动将内容复制粘贴到各个平台,这不仅耗时耗力,还容易导致格式错乱和品牌信息不一致。
与此同时,WordPress作为全球最流行的内容管理系统,占据了互联网上超过40%的网站份额。它强大的可扩展性和开源特性使其成为实现自动化内容分发的理想平台。通过代码二次开发,我们可以在WordPress中集成各种互联网小工具,实现内容的一键多平台分发,大大提高工作效率。
本教程将带领您一步步实现这一目标,从基础概念到实际代码实现,最终打造一个功能完善的自动化内容分发系统。
第一部分:理解多平台内容分发的基本原理
1.1 内容分发的技术架构
多平台内容分发的核心在于API(应用程序编程接口)的使用。大多数主流社交平台和内容聚合网站都提供了API,允许开发者以编程方式发布内容、管理账户和获取分析数据。
典型的内容分发流程包括:
- 内容创建与格式化
- 目标平台身份验证
- 内容转换与适配
- API调用与发布
- 发布结果跟踪与记录
1.2 WordPress作为分发中心的优势
WordPress本身已经是一个强大的内容管理系统,通过二次开发可以将其转变为内容分发中心:
- 内置的内容创建和编辑工具
- 丰富的插件生态系统
- 灵活的用户权限管理
- 强大的数据库支持
- 活跃的开发者社区
1.3 常用互联网小工具功能概览
在内容分发过程中,以下小工具功能将大大提高效率:
- 社交媒体分享按钮
- 内容自动摘要生成
- 多平台发布计划
- 发布效果分析面板
- 内容格式自动转换器
第二部分:搭建WordPress开发环境
2.1 本地开发环境配置
在开始代码开发之前,我们需要搭建一个合适的WordPress开发环境:
// 示例:本地WordPress环境配置要点
// 1. 安装本地服务器环境(如XAMPP、MAMP或Local by Flywheel)
// 2. 下载最新版WordPress并解压到服务器目录
// 3. 创建数据库并配置wp-config.php文件
// 4. 安装WordPress并设置管理员账户
// wp-config.php数据库配置示例
define('DB_NAME', 'your_database_name');
define('DB_USER', 'your_database_user');
define('DB_PASSWORD', 'your_database_password');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8mb4');
2.2 开发工具与资源准备
- 代码编辑器:VS Code、PHPStorm或Sublime Text
- 版本控制:Git和GitHub/GitLab账户
- 调试工具:Query Monitor、Debug Bar插件
- API测试工具:Postman或Insomnia
2.3 创建自定义插件框架
我们将创建一个独立插件来实现所有功能,避免修改主题文件:
<?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('MPCD_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('MPCD_PLUGIN_URL', plugin_dir_url(__FILE__));
define('MPCD_VERSION', '1.0.0');
// 初始化插件
class MultiPlatformContentDistributor {
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('init', array($this, 'init'));
// 管理界面
add_action('admin_menu', array($this, 'add_admin_menu'));
// 文章发布钩子
add_action('publish_post', array($this, 'on_post_publish'), 10, 2);
}
public function activate() {
// 创建必要的数据库表
$this->create_database_tables();
// 设置默认选项
$this->set_default_options();
// 刷新重写规则
flush_rewrite_rules();
}
public function deactivate() {
// 清理临时数据
// 注意:不删除用户设置和发布记录
flush_rewrite_rules();
}
public function init() {
// 加载文本域
load_plugin_textdomain('mpcd', false, dirname(plugin_basename(__FILE__)) . '/languages');
}
// 其他方法将在后续章节实现
}
// 启动插件
MultiPlatformContentDistributor::get_instance();
?>
第三部分:实现多平台API连接
3.1 平台API配置管理
我们需要创建一个管理界面来配置各个平台的API密钥和设置:
// 在MultiPlatformContentDistributor类中添加以下方法
public function add_admin_menu() {
add_menu_page(
'多平台分发设置',
'内容分发',
'manage_options',
'mpcd-settings',
array($this, 'render_settings_page'),
'dashicons-share',
30
);
add_submenu_page(
'mpcd-settings',
'平台配置',
'平台配置',
'manage_options',
'mpcd-platforms',
array($this, 'render_platforms_page')
);
add_submenu_page(
'mpcd-settings',
'发布记录',
'发布记录',
'manage_options',
'mpcd-logs',
array($this, 'render_logs_page')
);
}
public function render_settings_page() {
?>
<div class="wrap">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<div class="mpcd-dashboard">
<div class="mpcd-stats">
<h2>分发统计</h2>
<div class="stats-grid">
<div class="stat-card">
<h3>今日发布</h3>
<p class="stat-number"><?php echo $this->get_today_posts_count(); ?></p>
</div>
<div class="stat-card">
<h3>总发布数</h3>
<p class="stat-number"><?php echo $this->get_total_posts_count(); ?></p>
</div>
<div class="stat-card">
<h3>平台覆盖</h3>
<p class="stat-number"><?php echo $this->get_platforms_count(); ?></p>
</div>
</div>
</div>
<div class="mpcd-quick-actions">
<h2>快速操作</h2>
<button class="button button-primary" id="mpcd-test-all">测试所有平台连接</button>
<button class="button" id="mpcd-clear-logs">清理旧日志</button>
</div>
</div>
</div>
<style>
.mpcd-stats .stats-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
margin: 20px 0;
}
.stat-card {
background: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.stat-number {
font-size: 2em;
font-weight: bold;
color: #2271b1;
margin: 10px 0 0;
}
</style>
<script>
jQuery(document).ready(function($) {
$('#mpcd-test-all').on('click', function() {
// AJAX测试所有平台连接
});
});
</script>
<?php
}
3.2 主流平台API集成示例
以下是几个主流平台的API集成示例:
// 平台API基类
abstract class MPCD_Platform {
protected $platform_name;
protected $api_key;
protected $api_secret;
protected $access_token;
abstract public function authenticate();
abstract public function publish($content);
abstract public function test_connection();
public function __construct($config) {
$this->api_key = $config['api_key'] ?? '';
$this->api_secret = $config['api_secret'] ?? '';
$this->access_token = $config['access_token'] ?? '';
}
}
// 微信公众号平台实现
class MPCD_WeChat extends MPCD_Platform {
protected $platform_name = 'wechat';
public function authenticate() {
// 微信公众号OAuth认证流程
$auth_url = 'https://api.weixin.qq.com/cgi-bin/token';
$params = array(
'grant_type' => 'client_credential',
'appid' => $this->api_key,
'secret' => $this->api_secret
);
$response = wp_remote_get(add_query_arg($params, $auth_url));
if (is_wp_error($response)) {
return false;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['access_token'])) {
$this->access_token = $body['access_token'];
update_option('mpcd_wechat_token', array(
'token' => $this->access_token,
'expires' => time() + 7000 // 微信token有效期为7200秒
));
return true;
}
return false;
}
public function publish($content) {
if (!$this->access_token) {
if (!$this->authenticate()) {
return array('success' => false, 'message' => '认证失败');
}
}
$api_url = 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=' . $this->access_token;
$wechat_content = array(
'articles' => array(
array(
'title' => $content['title'],
'thumb_media_id' => $this->upload_image($content['featured_image']),
'author' => $content['author'],
'digest' => wp_trim_words(strip_tags($content['content']), 100),
'show_cover_pic' => 1,
'content' => $this->format_content_for_wechat($content['content']),
'content_source_url' => $content['url']
)
)
);
$response = wp_remote_post($api_url, array(
'body' => json_encode($wechat_content, JSON_UNESCAPED_UNICODE),
'headers' => array('Content-Type' => 'application/json')
));
// 处理响应
return $this->handle_response($response);
}
private function format_content_for_wechat($content) {
// 转换WordPress内容为微信公众号格式
$content = preg_replace('/<img[^>]+>/i', '', $content); // 移除img标签
$content = strip_tags($content, '<p><br><strong><em><h1><h2><h3><h4><h5><h6>');
return $content;
}
}
// 微博平台实现
class MPCD_Weibo extends MPCD_Platform {
protected $platform_name = 'weibo';
public function publish($content) {
$api_url = 'https://api.weibo.com/2/statuses/share.json';
// 微博有字数限制,需要处理
$weibo_content = $content['title'] . ' ' . $content['url'];
if (mb_strlen($weibo_content) > 140) {
$weibo_content = mb_substr($weibo_content, 0, 137) . '...';
}
$params = array(
'access_token' => $this->access_token,
'status' => $weibo_content
);
// 如果有特色图片,上传图片
if (!empty($content['featured_image'])) {
$pic_id = $this->upload_pic($content['featured_image']);
if ($pic_id) {
$params['pic_id'] = $pic_id;
}
}
$response = wp_remote_post($api_url, array(
'body' => $params
));
return $this->handle_response($response);
}
}
第四部分:内容一键分发功能实现
4.1 文章发布钩子与自动分发
// 在MultiPlatformContentDistributor类中添加文章发布处理
public function on_post_publish($post_id, $post) {
// 检查是否自动分发
$auto_distribute = get_option('mpcd_auto_distribute', true);
if (!$auto_distribute || wp_is_post_revision($post_id)) {
return;
}
// 检查文章类型
$allowed_types = apply_filters('mpcd_allowed_post_types', array('post'));
if (!in_array($post->post_type, $allowed_types)) {
return;
}
// 准备分发内容
$content = $this->prepare_content_for_distribution($post);
// 获取启用的平台
$enabled_platforms = $this->get_enabled_platforms();
// 分发到各个平台
$results = array();
foreach ($enabled_platforms as $platform) {
$platform_instance = $this->get_platform_instance($platform);
if ($platform_instance) {
$result = $platform_instance->publish($content);
$results[$platform] = $result;
// 记录日志
$this->log_distribution($post_id, $platform, $result);
}
}
// 保存分发结果到文章meta
update_post_meta($post_id, '_mpcd_distribution_results', $results);
update_post_meta($post_id, '_mpcd_distributed_at', current_time('mysql'));
}
private function prepare_content_for_distribution($post) {
$content = array(
'title' => get_the_title($post),
'content' => apply_filters('the_content', $post->post_content),
'excerpt' => $post->post_excerpt ?: wp_trim_words(strip_tags($post->post_content), 55),
'url' => get_permalink($post),
'author' => get_the_author_meta('display_name', $post->post_author),
'categories' => wp_get_post_categories($post->ID, array('fields' => 'names')),
'tags' => wp_get_post_tags($post->ID, array('fields' => 'names')),
'featured_image' => get_the_post_thumbnail_url($post, 'full')
);
// 应用过滤器允许修改内容
return apply_filters('mpcd_prepared_content', $content, $post);
}
private function get_enabled_platforms() {
$platforms = get_option('mpcd_enabled_platforms', array());
return is_array($platforms) ? $platforms : array();
}
4.2 手动分发与批量处理
// 添加文章编辑页面的分发按钮
public function add_post_distribution_meta_box() {
add_meta_box(
'mpcd-distribution-box',
'多平台分发',
array($this, 'render_distribution_meta_box'),
'post',
'side',
'high'
);
}
public function render_distribution_meta_box($post) {
$distributed = get_post_meta($post->ID, '_mpcd_distributed_at', true);
$results = get_post_meta($post->ID, '_mpcd_distribution_results', true);
?>
<div class="mpcd-distribution-controls">
<?php if ($distributed): ?>
<p>已分发于: <?php echo date('Y-m-d H:i', strtotime($distributed)); ?></p>
<button type="button" class="button" id="mpcd-redistribute">重新分发</button>
<button type="button" class="button" id="mpcd-view-results">查看结果</button>
<?php else: ?>
<button type="button" class="button button-primary" id="mpcd-distribute-now">立即分发</button>
<?php endif; ?>
<div class="platform-selection" style="margin-top: 15px;">
<p><strong>选择平台:</strong></p>
<?php
$platforms = $this->get_available_platforms();
foreach ($platforms as $platform_id => $platform_name):
$enabled = in_array($platform_id, $this->get_enabled_platforms());
?>
<label style="display: block; margin-bottom: 5px;">
<input type="checkbox"
name="mpcd_platforms[]"
value="<?php echo esc_attr($platform_id); ?>"
<?php checked($enabled); ?>>
<?php echo esc_html($platform_name); ?>
</label>
<?php endforeach; ?>
</div>
</div>
<script>
ready(function($) {
$('#mpcd-distribute-now').on('click', function() {
var platforms = [];
$('input[name="mpcd_platforms[]"]:checked').each(function() {
platforms.push($(this).val());
});
if (platforms.length === 0) {
alert('请至少选择一个平台');
return;
}
$(this).prop('disabled', true).text('分发中...');
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'mpcd_distribute_post',
post_id: <?php echo $post->ID; ?>,
platforms: platforms,
nonce: '<?php echo wp_create_nonce("mpcd_distribute_{$post->ID}"); ?>'
},
success: function(response) {
if (response.success) {
alert('分发成功!');
location.reload();
} else {
alert('分发失败: ' + response.data);
}
},
error: function() {
alert('请求失败,请检查网络连接');
}
});
});
});
</script>
<?php
}
// AJAX处理分发请求
public function handle_ajax_distribution() {
check_ajax_referer('mpcd_distribute_' . $_POST['post_id'], 'nonce');
$post_id = intval($_POST['post_id']);
$platforms = isset($_POST['platforms']) ? (array)$_POST['platforms'] : array();
if (!current_user_can('edit_post', $post_id)) {
wp_die('权限不足');
}
$post = get_post($post_id);
if (!$post) {
wp_die('文章不存在');
}
$content = $this->prepare_content_for_distribution($post);
$results = array();
foreach ($platforms as $platform_id) {
$platform_instance = $this->get_platform_instance($platform_id);
if ($platform_instance) {
$result = $platform_instance->publish($content);
$results[$platform_id] = $result;
$this->log_distribution($post_id, $platform_id, $result);
}
}
update_post_meta($post_id, '_mpcd_distribution_results', $results);
update_post_meta($post_id, '_mpcd_distributed_at', current_time('mysql'));
wp_send_json_success('分发完成');
}
## 第五部分:集成常用互联网小工具
### 5.1 智能内容摘要生成器
class MPCD_Content_Summarizer {
public static function generate_summary($content, $max_length = 200) {
// 移除HTML标签
$plain_text = wp_strip_all_tags($content);
// 如果内容已经足够短,直接返回
if (mb_strlen($plain_text) <= $max_length) {
return $plain_text;
}
// 尝试查找文章摘要段落
$summary = self::extract_summary_paragraph($plain_text, $max_length);
// 如果没有找到合适的段落,使用智能截取
if (empty($summary)) {
$summary = self::smart_truncate($plain_text, $max_length);
}
return apply_filters('mpcd_generated_summary', $summary, $content, $max_length);
}
private static function extract_summary_paragraph($text, $max_length) {
// 分割成段落
$paragraphs = preg_split('/ns*n/', $text);
foreach ($paragraphs as $paragraph) {
$paragraph = trim($paragraph);
$length = mb_strlen($paragraph);
// 寻找长度合适的段落(在最大长度的60%-100%之间)
if ($length >= $max_length * 0.6 && $length <= $max_length) {
return $paragraph;
}
}
// 如果没有合适长度的段落,找第一个较长的段落并截取
foreach ($paragraphs as $paragraph) {
$paragraph = trim($paragraph);
if (mb_strlen($paragraph) > 50) {
return self::smart_truncate($paragraph, $max_length);
}
}
return '';
}
private static function smart_truncate($text, $max_length) {
// 在句子边界处截断
$sentences = preg_split('/(?<=[。!?.!?])s+/u', $text);
$result = '';
foreach ($sentences as $sentence) {
if (mb_strlen($result . $sentence) > $max_length) {
break;
}
$result .= $sentence;
}
// 如果没有完整的句子,在词边界处截断
if (empty($result)) {
$result = mb_substr($text, 0, $max_length - 3);
// 避免截断在单词中间
$last_space = mb_strrpos($result, ' ');
if ($last_space > $max_length * 0.7) {
$result = mb_substr($result, 0, $last_space);
}
$result .= '...';
}
return $result;
}
}
// 集成到分发系统中
add_filter('mpcd_prepared_content', function($content, $post) {
if (empty($content['excerpt']) || strlen($content['excerpt']) < 50) {
$content['excerpt'] = MPCD_Content_Summarizer::generate_summary(
$content['content'],
150
);
}
return $content;
}, 10, 2);
### 5.2 多平台发布计划器
class MPCD_Scheduler {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('mpcd_scheduled_distribution', array($this, 'process_scheduled_distribution'), 10, 2);
add_action('init', array($this, 'schedule_cron_jobs'));
}
public function schedule_cron_jobs() {
if (!wp_next_scheduled('mpcd_hourly_distribution_check')) {
wp_schedule_event(time(), 'hourly', 'mpcd_hourly_distribution_check');
}
add_action('mpcd_hourly_distribution_check', array($this, 'check_scheduled_distributions'));
}
public function check_scheduled_distributions() {
global $wpdb;
$table_name = $wpdb->prefix . 'mpcd_schedules';
$scheduled = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$table_name}
WHERE scheduled_time <= %s
AND status = 'pending'
LIMIT 10",
current_time('mysql')
)
);
foreach ($scheduled as $schedule) {
$this->process_schedule($schedule);
}
}
public function process_schedule($schedule) {
global $wpdb;
$table_name = $wpdb->prefix . 'mpcd_schedules';
// 更新状态为处理中
$wpdb->update(
$table_name,
array('status' => 'processing'),
array('id' => $schedule->id)
);
$post = get_post($schedule->post_id);
if (!$post) {
$wpdb->update(
$table_name,
array(
'status' => 'failed',
'error_message' => '文章不存在'
),
array('id' => $schedule->id)
);
return;
}
// 准备内容
$distributor = MultiPlatformContentDistributor::get_instance();
$content = $distributor->prepare_content_for_distribution($post);
// 分发到指定平台
$platforms = maybe_unserialize($schedule->platforms);
$results = array();
foreach ($platforms as $platform_id) {
$platform_instance = $distributor->get_platform_instance($platform_id);
if ($platform_instance) {
$result = $platform_instance->publish($content);
$results[$platform_id] = $result;
$distributor->log_distribution($schedule->post_id, $platform_id, $result);
}
}
// 更新状态
$wpdb->update(
$table_name,
array(
'status' => 'completed',
'completed_at' => current_time('mysql'),
'results' => maybe_serialize($results)
),
array('id' => $schedule->id)
);
// 更新文章meta
update_post_meta($schedule->post_id, '_mpcd_scheduled_distribution', $results);
}
public function create_schedule($post_id, $platforms, $scheduled_time) {
global $wpdb;
$table_name = $wpdb->prefix . 'mpcd_schedules';
return $wpdb->insert(
$table_name,
array(
'post_id' => $post_id,
'platforms' => maybe_serialize($platforms),
'scheduled_time' => $scheduled_time,
'status' => 'pending',
'created_at' => current_time('mysql')
)
);
}
public function get_schedules($args = array()) {
global $wpdb;
$defaults = array(
'post_id' => null,
'status' => null,
'limit' => 50,
'offset' => 0
);
$args = wp_parse_args($args, $defaults);
$table_name = $wpdb->prefix . 'mpcd_schedules';
$where = array('1=1');
$params = array();
if ($args['post_id']) {
$where[] = 'post_id = %d';
$params[] = $args['post_id'];
}
if ($args['status']) {
$where[] = 'status = %s';
$params[] = $args['status'];
}
$where_clause = implode(' AND ', $where);
$query = "SELECT * FROM {$table_name} WHERE {$where_clause}
ORDER BY scheduled_time DESC
LIMIT %d OFFSET %d";
$params[] = $args['limit'];
$params[] = $args['offset'];
if (!empty($params)) {
$query = $wpdb->prepare($query, $params);
}
return $wpdb->get_results($query);
}
}
### 5.3 发布效果分析面板
class MPCD_Analytics {
public static function get_distribution_stats($period = '7days') {
global $wpdb;
$logs_table = $wpdb->prefix . 'mpcd_distribution_logs';
// 根据时间段设置日期范围
$date_range = self::get_date_range($period);
$stats = array(
'total_posts' => 0,
'successful' => 0,
'failed' => 0,
'by_platform' => array(),
'by_day' => array()
);
// 获取总体统计
$overall_stats = $wpdb->get_row(
$wpdb->prepare(
"SELECT
COUNT(*) as total,
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful,
SUM(CASE WHEN success = 0 THEN 1 ELSE 0 END) as failed
FROM {$logs_table}
WHERE distributed_at >= %s AND distributed_at <= %s",
$date_range['start'],
$date_range['end']
)
);
if ($overall_stats) {
$stats['total_posts'] = intval($overall_stats->total);
$stats['successful'] = intval($overall_stats->successful);
$stats['failed'] = intval($overall_stats->failed);
}
// 按平台统计
$platform_stats = $wpdb->get_results(
$wpdb->prepare(
"SELECT
platform,
COUNT(*) as total,
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful
FROM {$logs_table}
WHERE distributed_at >= %s AND distributed_at <= %s
GROUP BY platform
ORDER BY total DESC",
$date_range['start'],
$date_range['end']
)
);
foreach ($platform_stats as $platform_stat) {
$stats['by_platform'][$platform_stat->platform] = array(
'total' => intval($platform_stat->total),
'successful' => intval($platform_stat->successful),
'success_rate' => $platform_stat->total > 0 ?
round($platform_stat->successful / $platform_stat->total * 100, 1) : 0
);
}
// 按日期统计
$daily_stats = $wpdb->get_results(
$wpdb->prepare(
"SELECT
DATE(distributed_at) as date,
COUNT(*) as total,
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful
FROM {$logs_table}
WHERE distributed_at >= %s AND distributed_at <= %s
GROUP BY DATE(distributed_at)
ORDER BY date",
$date_range['start'],
$date_range['end']
)
);
foreach ($daily_stats as $daily_stat) {
$stats['by_day'][$daily_stat->date] = array(
'total' => intval($daily_stat->total),
'successful' => intval($daily_stat->successful)
);
}
return $stats;
}
public static function get_top_performing_posts($limit = 10) {
global $wpdb;
$logs_table = $wpdb->prefix . 'mpcd_distribution_logs';
$query = $wpdb->prepare(
"SELECT
post_id,
COUNT(*) as total_distributions,
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful_distributions
FROM {$logs_table}
WHERE post_id IS NOT NULL
GROUP BY post_id
ORDER BY total_distributions DESC
LIMIT %d",
$limit
);
$results = $wpdb->get_results($query);
$posts = array();
foreach ($results as $result) {
$post = get_post($result->post_id);
if ($post) {
$posts[] = array(
'post' => $post,
'stats' => array(
'total' => intval($result->total_distributions),
'successful' => intval($result->successful_distributions),
'success_rate' => $result->total_distributions > 0 ?
round($result->successful_distributions / $result->total_distributions * 100, 1) : 0
)
);
}
}
return $posts;
}
private static function get_date_range($period) {
$end_date = current_time('mysql');
switch ($period) {
case 'today':
$start_date = date('Y-m-d 00:00:00', strtotime($end_date));
break;
case 'yesterday':
$start_date = date('Y-m-d 00:00:00', strtotime('-1 day', strtotime($end_date)));
$end_date = date('Y-m-d 23:59:59', strtotime('-1 day', strtotime($end_date)));
break;
case '7days':
$start_date = date('Y-m-d 00:00:00', strtotime('-7 days', strtotime($end_date)));
break;
case '30days':
$start_date = date('Y-m-d 00:00:00', strtotime('-30 days', strtotime($end_date)));
break;
default:
$start_date = date('Y-m-d 00:00:00', strtotime('-7 days', strtotime($end_date)));
}
return array(
'start' => $start_date,
'end' => $end_date
);
}
}
## 第六部分:高级功能与优化
### 6.1 内容格式自动转换器
class MPCD_Content_Transformer {
public static function transform_for_platform($content, $platform) {
$transformers = array(
'wechat' => array('self', 'transform_for_wechat'),
'weibo' => array('self', 'transform_for_weibo'),
'zhihu' => array('self', 'transform_for_zhihu'),
'toutiao' => array('self', 'transform_for_toutiao'),
'default' => array('self', 'transform_default')
);
$transformer = isset($transformers[$platform]) ?
$transformers[$platform] : $transformers['default'];
return call_user_func($transformer, $content);
}
private static function transform_for_wechat($content) {
// 微信公众号特殊处理
$transformed = $content;
// 移除所有外部链接(微信不允许)
$transformed['content'] = preg_replace(
'/<as[^>]*href=["'](?!https?://mp.weixin.qq.com)[^"']*["'][^>]*>(.*?)</a>/i',
'$1',
$transformed['content']
);
// 转换图片为微信格式
$transformed['content'] = preg_replace_callback(
'/<imgs[^>]*src=["']([^"']+)["'][^>]*>/i',
array('self', 'convert_image_for_wechat'),
$transformed['content']
);
//
