文章目录
-
- 在当今数字营销时代,社交媒体已成为企业与个人品牌推广不可或缺的渠道。然而,手动将WordPress网站内容同步到各个社交媒体平台不仅耗时耗力,还容易出错。据统计,营销人员平均每周花费6-15小时在社交媒体内容管理上,其中大部分时间用于内容分发和调度。 通过WordPress代码二次开发实现自动化社交媒体同步,不仅可以节省大量时间,还能确保内容在不同平台间的一致性,提高发布效率。本教程将引导您从零开始,通过自定义开发实现这一功能,同时探索如何将常用互联网小工具集成到WordPress中。
-
- WordPress的强大之处在于其完善的钩子(Hooks)系统,包括动作(Actions)和过滤器(Filters)。要实现自动化社交媒体同步,我们需要利用这些钩子在适当的时候触发我们的代码。 // 示例:基本的WordPress钩子使用 add_action('publish_post', 'sync_to_social_media', 10, 2); function sync_to_social_media($post_id, $post) { // 当文章发布时执行社交媒体同步 // 具体实现代码将在后续部分添加 }
- 为了避免主题更新导致代码丢失,我们建议将功能实现为独立插件: 在wp-content/plugins/目录下创建新文件夹social-auto-sync 创建主插件文件social-auto-sync.php 添加插件头部信息: <?php /** * Plugin Name: 社交媒体自动同步 * Plugin URI: https://yourwebsite.com/ * Description: 自动将WordPress内容同步到各大社交媒体平台 * Version: 1.0.0 * Author: 您的名字 * License: GPL v2 or later */
- 确保您的开发环境满足以下要求: WordPress 5.0+ PHP 7.4+ 启用curl扩展(用于API调用) 文本编辑器或IDE(如VS Code、PHPStorm)
-
- 要实现自动化同步,首先需要获取各社交媒体平台的API访问权限: Twitter(X):通过Twitter开发者门户创建应用 Facebook:使用Facebook开发者工具创建应用并获取访问令牌 LinkedIn:在LinkedIn开发者门户创建应用 Instagram:通过Facebook开发者工具(Instagram属于Facebook生态)
- 永远不要在代码中硬编码API密钥。使用WordPress选项API安全存储: // 创建设置页面存储API密钥 add_action('admin_menu', 'social_sync_add_admin_menu'); function social_sync_add_admin_menu() { add_options_page( '社交媒体同步设置', '社媒同步', 'manage_options', 'social-sync-settings', 'social_sync_settings_page' ); } function social_sync_settings_page() { ?> <div class="wrap"> <h1>社交媒体同步设置</h1> <form method="post" action="options.php"> <?php settings_fields('social_sync_settings_group'); do_settings_sections('social-sync-settings'); submit_button(); ?> </form> </div> <?php } // 注册设置 add_action('admin_init', 'social_sync_settings_init'); function social_sync_settings_init() { register_setting('social_sync_settings_group', 'social_sync_settings'); add_settings_section( 'social_sync_api_section', 'API设置', null, 'social-sync-settings' ); add_settings_field( 'twitter_api_key', 'Twitter API密钥', 'social_sync_api_key_callback', 'social-sync-settings', 'social_sync_api_section', ['label_for' => 'twitter_api_key'] ); // 添加更多API字段... } function social_sync_api_key_callback($args) { $options = get_option('social_sync_settings'); $id = $args['label_for']; $value = isset($options[$id]) ? $options[$id] : ''; ?> <input type="password" id="<?php echo esc_attr($id); ?>" name="social_sync_settings[<?php echo esc_attr($id); ?>]" value="<?php echo esc_attr($value); ?>" class="regular-text"> <?php }
-
- 当WordPress文章发布时,自动提取内容并分享到社交媒体: // 监听文章发布 add_action('publish_post', 'auto_share_on_publish', 10, 2); function auto_share_on_publish($post_id, $post) { // 防止无限循环 if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return; if (wp_is_post_revision($post_id)) return; // 检查是否已经分享过 if (get_post_meta($post_id, '_social_shared', true)) return; // 获取文章信息 $title = get_the_title($post_id); $excerpt = wp_trim_words(get_the_excerpt($post_id), 30, '...'); $permalink = get_permalink($post_id); $featured_image = get_the_post_thumbnail_url($post_id, 'medium'); // 构建分享内容 $message = $title . "nn" . $excerpt . "nn阅读更多: " . $permalink; // 分享到各个平台 $results = []; // Twitter分享 if (get_option('social_sync_twitter_enable')) { $results['twitter'] = share_to_twitter($message, $featured_image); } // Facebook分享 if (get_option('social_sync_facebook_enable')) { $results['facebook'] = share_to_facebook($message, $permalink, $featured_image); } // LinkedIn分享 if (get_option('social_sync_linkedin_enable')) { $results['linkedin'] = share_to_linkedin($title, $excerpt, $permalink, $featured_image); } // 标记为已分享 update_post_meta($post_id, '_social_shared', true); update_post_meta($post_id, '_social_share_results', $results); // 记录日志 social_sync_log('文章发布同步', $post_id, $results); }
- function share_to_twitter($message, $image_url = null) { $settings = get_option('social_sync_settings'); $api_key = $settings['twitter_api_key'] ?? ''; $api_secret = $settings['twitter_api_secret'] ?? ''; $access_token = $settings['twitter_access_token'] ?? ''; $access_secret = $settings['twitter_access_secret'] ?? ''; if (empty($api_key) || empty($access_token)) { return ['success' => false, 'error' => 'API凭证未配置']; } // 使用Twitter API v2 $endpoint = 'https://api.twitter.com/2/tweets'; // 构建请求数据 $data = ['text' => substr($message, 0, 280)]; // Twitter限制280字符 // 如果有图片,先上传媒体 if ($image_url) { $media_id = upload_twitter_media($image_url, $api_key, $api_secret, $access_token, $access_secret); if ($media_id) { $data['media'] = ['media_ids' => [$media_id]]; } } // 发送请求 $response = wp_remote_post($endpoint, [ 'headers' => [ 'Authorization' => 'Bearer ' . $access_token, 'Content-Type' => 'application/json', ], 'body' => json_encode($data), 'timeout' => 30, ]); if (is_wp_error($response)) { return ['success' => false, 'error' => $response->get_error_message()]; } $body = json_decode(wp_remote_retrieve_body($response), true); if (isset($body['data']['id'])) { return ['success' => true, 'tweet_id' => $body['data']['id']]; } else { return ['success' => false, 'error' => $body['errors'][0]['detail'] ?? '未知错误']; } } function upload_twitter_media($image_url, $api_key, $api_secret, $access_token, $access_secret) { // 下载图片 $image_data = wp_remote_get($image_url); if (is_wp_error($image_data)) { return false; } $image_content = wp_remote_retrieve_body($image_data); // 上传到Twitter媒体端点 $upload_endpoint = 'https://upload.twitter.com/1.1/media/upload.json'; $response = wp_remote_post($upload_endpoint, [ 'headers' => [ 'Authorization' => 'OAuth oauth_consumer_key="' . $api_key . '", oauth_nonce="' . wp_generate_uuid4() . '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' . time() . '", oauth_token="' . $access_token . '", oauth_version="1.0"', ], 'body' => [ 'media_data' => base64_encode($image_content) ], 'timeout' => 30, ]); if (is_wp_error($response)) { return false; } $body = json_decode(wp_remote_retrieve_body($response), true); return $body['media_id_string'] ?? false; }
- function share_to_facebook($message, $link, $image_url = null) { $settings = get_option('social_sync_settings'); $page_id = $settings['facebook_page_id'] ?? ''; $access_token = $settings['facebook_access_token'] ?? ''; if (empty($page_id) || empty($access_token)) { return ['success' => false, 'error' => 'Facebook配置不完整']; } $endpoint = "https://graph.facebook.com/v12.0/{$page_id}/feed"; // 构建请求数据 $data = [ 'message' => $message, 'link' => $link, 'access_token' => $access_token, ]; // 如果有图片,附加图片URL if ($image_url) { $data['picture'] = $image_url; } // 发送请求 $response = wp_remote_post($endpoint, [ 'body' => $data, 'timeout' => 30, ]); if (is_wp_error($response)) { return ['success' => false, 'error' => $response->get_error_message()]; } $body = json_decode(wp_remote_retrieve_body($response), true); if (isset($body['id'])) { return ['success' => true, 'post_id' => $body['id']]; } else { return ['success' => false, 'error' => $body['error']['message'] ?? '未知错误']; } }
-
- 除了即时发布,还可以实现定时发布到社交媒体: // 创建自定义计划任务 add_action('social_sync_scheduled_share', 'scheduled_social_share', 10, 1); function scheduled_social_share($post_id) { $post = get_post($post_id); if (!$post || $post->post_status !== 'future') { return; } // 执行社交媒体分享 auto_share_on_publish($post_id, $post); } // 当定时文章发布时触发 add_action('publish_future_post', 'schedule_social_share_on_publish', 10, 1); function schedule_social_share_on_publish($post_id) { $post = get_post($post_id); $publish_time = strtotime($post->post_date); // 安排在文章发布时间执行社交媒体分享 wp_schedule_single_event($publish_time, 'social_sync_scheduled_share', [$post_id]); }
- 不同社交媒体平台有不同的内容要求,需要针对性地优化: function format_content_for_platform($content, $platform, $post_id) { $formatted = $content; switch ($platform) { case 'twitter': // Twitter: 280字符限制,添加话题标签 $formatted = substr($content, 0, 250); // 留空间给链接和标签 // 自动提取或添加话题标签 $tags = get_post_tags($post_id); if ($tags) { $tag_names = array_slice(wp_list_pluck($tags, 'name'), 0, 3); $hashtags = ' ' . implode(' ', array_map(function($tag) { return '#' . preg_replace('/s+/', '', $tag); }, $tag_names)); if (strlen($formatted . $hashtags) <= 280) { $formatted .= $hashtags; } } break; case 'linkedin': // LinkedIn: 更专业的语气,可以更长 $formatted = $content . "nn#WordPress #内容营销"; break; case 'facebook': // Facebook: 更友好,可以添加表情符号 $formatted = "📢 新文章发布!nn" . $content . "nn点击链接阅读全文 👇"; break; } return $formatted; }
- 完善的错误处理是自动化系统可靠性的关键: function social_sync_log($action, $post_id, $data) { $log_entry = [ 'timestamp' => current_time('mysql'), 'action' => $action, 'post_id' => $post_id, 'data' => $data, 'ip' => $_SERVER['REMOTE_ADDR'] ?? '未知', ]; // 获取现有日志 $logs = get_option('social_sync_logs', []); // 限制日志数量(保留最近100条) if (count($logs) >= 100) { array_shift($logs); } // 添加新日志 $logs[] = $log_entry; // 保存日志 update_option('social_sync_logs', $logs, false); } // 创建日志查看页面 add_action('admin_menu', 'social_sync_logs_page'); function social_sync_logs_page() { add_submenu_page( 'options-general.php', '社交媒体同步日志', '社媒同步日志', 'manage_options', 'social-sync-logs', 'social_sync_logs_page_content' ); } function social_sync_logs_page_content() { $logs = get_option('social_sync_logs', []); ?> <div class="wrap"> <h1>社交媒体同步日志</h1> <?php if (empty($logs)): ?> <p>暂无日志记录。</p> <?php else: ?> <table class="wp-list-table widefat fixed striped"> <thead> <tr> <th>时间</th> <th>操作</th> <th>文章ID</th> <th>结果</th> <th>IP地址</th> </tr> </thead> <tbody> <?php foreach (array_reverse($logs) as $log): ?> <tr> <td><?php echo esc_html($log['timestamp']); ?></td> <td><?php echo esc_html($log['action']); ?></td> <td> <?php if ($log['post_id']): ?> <a href="<?php echo get_edit_post_link($log['post_id']); ?>"> 文章#<?php echo esc_html($log['post_id']); ?> </a> <?php else: ?> N/A <?php endif; ?> </td> <td> <?php if (is_array($log['data'])) { foreach ($log['data'] as $platform => $result) { echo esc_html($platform) . ': ' . ($result['success'] ? '成功' : '失败') . '<br>'; if (!$result['success'] && isset($result['error'])) { echo '<small style="color:red;">' . esc_html($result['error']) . '</small><br>'; } } } ?> </td> <td><?php echo esc_html($log['ip']); ?></td> </tr> <?php endforeach; ?> </tbody> </table> <form method="post" style="margin-top: 20px;"> <?php wp_nonce_field('clear_social_sync_logs', 'social_sync_nonce'); ?> <input type="hidden" name="action" value="clear_logs"> <input type="submit" class="button button-secondary" value="清空日志"> </form> <?php endif; ?> </div> <?php // 处理清空日志请求 if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'clear_logs' && `clear_social_sync_logs', 'social_sync_nonce')) { update_option('social_sync_logs', []); echo '<div class="notice notice-success is-dismissible"><p>日志已清空。</p></div>'; } } ## 第五部分:常用互联网小工具集成 ### 5.1 URL短链接生成器 集成短链接服务,优化社交媒体分享: function generate_short_url($long_url, $service = 'bitly') { $settings = get_option('social_sync_settings'); switch ($service) { case 'bitly': $access_token = $settings['bitly_access_token'] ?? ''; if (empty($access_token)) return $long_url; $endpoint = 'https://api-ssl.bitly.com/v4/shorten'; $response = wp_remote_post($endpoint, [ 'headers' => [ 'Authorization' => 'Bearer ' . $access_token, 'Content-Type' => 'application/json', ], 'body' => json_encode(['long_url' => $long_url]), 'timeout' => 15, ]); if (!is_wp_error($response)) { $body = json_decode(wp_remote_retrieve_body($response), true); if (isset($body['link'])) { return $body['link']; } } break; case 'tinyurl': $endpoint = 'https://tinyurl.com/api-create.php?url=' . urlencode($long_url); $response = wp_remote_get($endpoint); if (!is_wp_error($response)) { $short_url = wp_remote_retrieve_body($response); if (filter_var($short_url, FILTER_VALIDATE_URL)) { return $short_url; } } break; } return $long_url; // 失败时返回原链接 } // 在分享函数中使用短链接function auto_share_on_publish_with_shorturl($post_id, $post) { // ... 之前的代码 ... $permalink = get_permalink($post_id); $short_url = generate_short_url($permalink, 'bitly'); // 使用短链接构建消息 $message = $title . "nn" . $excerpt . "nn" . $short_url; // ... 后续分享代码 ... } ### 5.2 内容分析工具集成 集成内容分析功能,优化分享效果: function analyze_content_for_sharing($post_id) { $post = get_post($post_id); $content = $post->post_content; $title = $post->post_title; $analysis = [ 'readability_score' => calculate_readability($content), 'keyword_density' => get_keyword_density($content, $title), 'optimal_length' => check_length_optimization($content), 'image_count' => count_images_in_content($content), 'has_video' => has_video_content($content), ]; // 根据分析结果给出建议 $suggestions = generate_sharing_suggestions($analysis); return [ 'analysis' => $analysis, 'suggestions' => $suggestions, ]; } function calculate_readability($content) { // 实现Flesch-Kincaid可读性测试简化版 $text = strip_tags($content); $words = str_word_count($text); $sentences = preg_split('/[.!?]+/', $text); $sentence_count = count(array_filter($sentences)); if ($words === 0 || $sentence_count === 0) { return 0; } $average_words_per_sentence = $words / $sentence_count; $average_syllables_per_word = estimate_syllables($text) / $words; // Flesch Reading Ease公式 $score = 206.835 - (1.015 * $average_words_per_sentence) - (84.6 * $average_syllables_per_word); return round($score, 2); } function generate_sharing_suggestions($analysis) { $suggestions = []; if ($analysis['readability_score'] < 60) { $suggestions[] = '内容可读性较低,建议简化句子结构'; } if ($analysis['image_count'] === 0) { $suggestions[] = '建议添加相关图片以提高社交媒体参与度'; } if ($analysis['has_video']) { $suggestions[] = '检测到视频内容,建议在社交媒体上突出显示'; } return $suggestions; } ### 5.3 自动话题标签生成器 function generate_hashtags($content, $title, $count = 5) { // 提取关键词 $keywords = extract_keywords($content . ' ' . $title); // 过滤和排序关键词 $filtered_keywords = array_filter($keywords, function($word) { // 移除太短或太常见的词 return strlen($word) > 3 && !in_array(strtolower($word), [ 'this', 'that', 'with', 'from', 'have', 'were', 'they' ]); }); // 转换为话题标签 $hashtags = array_map(function($word) { // 移除特殊字符,转换为小写 $clean_word = preg_replace('/[^a-zA-Z0-9]/', '', $word); return '#' . ucfirst(strtolower($clean_word)); }, array_slice($filtered_keywords, 0, $count)); return $hashtags; } function extract_keywords($text) { // 移除HTML标签和特殊字符 $clean_text = strip_tags($text); $clean_text = preg_replace('/[^p{L}p{N}s]/u', ' ', $clean_text); // 分词 $words = preg_split('/s+/', $clean_text); // 统计词频 $word_counts = array_count_values(array_map('strtolower', $words)); // 按频率排序 arsort($word_counts); return array_keys($word_counts); } ## 第六部分:用户界面与交互优化 ### 6.1 文章编辑界面集成 在文章编辑界面添加社交媒体分享控制面板: add_action('add_meta_boxes', 'add_social_sync_meta_box'); function add_social_sync_meta_box() { add_meta_box( 'social_sync_meta_box', '社交媒体分享设置', 'render_social_sync_meta_box', 'post', 'side', 'high' ); } function render_social_sync_meta_box($post) { wp_nonce_field('social_sync_meta_box', 'social_sync_nonce'); $shared = get_post_meta($post->ID, '_social_shared', true); $share_results = get_post_meta($post->ID, '_social_share_results', true); ?> <div id="social-sync-controls"> <p> <label> <input type="checkbox" name="auto_share" value="1" <?php checked(!$shared); ?> <?php echo $shared ? 'disabled' : ''; ?>> 发布时自动分享到社交媒体 </label> </p> <?php if ($shared): ?> <div class="notice notice-success inline"> <p>✅ 已分享到社交媒体</p> <?php if ($share_results): ?> <ul style="margin: 5px 0; padding-left: 20px;"> <?php foreach ($share_results as $platform => $result): ?> <li> <?php echo esc_html(ucfirst($platform)); ?>: <?php echo $result['success'] ? '✅ 成功' : '❌ 失败'; ?> <?php if (!$result['success'] && isset($result['error'])): ?> <br><small style="color: #666;"><?php echo esc_html($result['error']); ?></small> <?php endif; ?> </li> <?php endforeach; ?> </ul> <?php endif; ?> </div> <p> <button type="button" id="reshare-button" class="button button-secondary"> 重新分享 </button> <span class="description">强制重新分享到所有平台</span> </p> <?php endif; ?> <div id="platform-selection" style="margin-top: 10px; <?php echo $shared ? 'display:none;' : ''; ?>"> <p><strong>选择分享平台:</strong></p> <?php $platforms = [ 'twitter' => 'Twitter', 'facebook' => 'Facebook', 'linkedin' => 'LinkedIn', ]; foreach ($platforms as $key => $label): $enabled = get_option("social_sync_{$key}_enable", true); ?> <p> <label> <input type="checkbox" name="share_platforms[]" value="<?php echo esc_attr($key); ?>" <?php checked($enabled); ?> <?php echo $enabled ? '' : 'disabled'; ?>> <?php echo esc_html($label); ?> <?php if (!$enabled): ?> <br><small style="color: #999;">(在设置中启用)</small> <?php endif; ?> </label> </p> <?php endforeach; ?> </div> <div id="custom-message" style="margin-top: 10px; display: none;"> <p><strong>自定义分享消息:</strong></p> <textarea name="custom_share_message" rows="3" style="width:100%;"></textarea> <p class="description">留空使用自动生成的消息</p> </div> <p> <a href="#" id="toggle-custom-message">自定义消息</a> | <a href="#" id="preview-share">预览</a> </p> </div> <script> jQuery(document).ready(function($) { // 切换自定义消息区域 $('#toggle-custom-message').click(function(e) { e.preventDefault(); $('#custom-message').toggle(); }); // 预览分享 $('#preview-share').click(function(e) { e.preventDefault(); $.ajax({ url: ajaxurl, type: 'POST', data: { action: 'preview_social_share', post_id: <?php echo $post->ID; ?>, nonce: '<?php echo wp_create_nonce("preview_share_{$post->ID}"); ?>' }, success: function(response) { if (response.success) { // 显示预览模态框 showPreviewModal(response.data); } } }); }); // 重新分享按钮 $('#reshare-button').click(function() { if (confirm('确定要重新分享这篇文章吗?')) { $.ajax({ url: ajaxurl, type: 'POST', data: { action: 'reshare_post', post_id: <?php echo $post->ID; ?>, nonce: '<?php echo wp_create_nonce("reshare_{$post->ID}"); ?>' }, success: function(response) { if (response.success) { location.reload(); } else { alert('重新分享失败:' + response.data); } } }); } }); function showPreviewModal(previews) { // 创建并显示预览模态框 // 实现模态框显示逻辑 } }); </script> <?php } ### 6.2 AJAX交互处理 add_action('wp_ajax_preview_social_share', 'handle_preview_social_share');add_action('wp_ajax_reshare_post', 'handle_reshare_post'); function handle_preview_social_share() { check_ajax_referer('preview_share_' . $_POST['post_id'], 'nonce'); $post_id = intval($_POST['post_id']); $post = get_post($post_id); if (!$post) { wp_die('文章不存在'); } $previews = []; $platforms = ['twitter', 'facebook', 'linkedin']; foreach ($platforms as $platform) { if (get_option("social_sync_{$platform}_enable")) { $message = generate_share_message($post, $platform); $previews[$platform] = [ 'message' => $message, 'length' => strlen($message), 'max_length' => $platform === 'twitter' ? 280 : 5000, ]; } } wp_send_json_success($previews); } function handle_reshare_post() { check_ajax_referer('reshare_' . $_POST['post_id'], 'nonce'); $post_id = intval($_POST['post_id']); $post = get_post($post_id); if (!$post) { wp_send_json_error('文章不存在'); } // 清除之前的分享标记 delete_post_meta($post_id, '_social_shared'); delete_post_meta($post_id, '_social_share_results'); // 重新分享 auto_share_on_publish($post_id, $post); wp_send_json_success('重新分享成功'); } ## 第七部分:性能优化与安全考虑 ### 7.1 异步处理优化 对于耗时的社交媒体API调用,使用异步处理避免阻塞: function async_share_to_social_media($post_id) { // 使用WordPress后台任务系统 if (!wp_next_scheduled('async_social_share', [$post_id])) { wp_schedule_single_event(time() + 5, 'async_social_share', [$post_id]); } } add_action('async_social_share', 'execute_async_social_share'); function execute_async_social_share($post_id) { $post = get_post($post_id); if ($post && $post->post_status === 'publish') { auto_share_on_publish($post_id, $post); } } // 修改发布钩子使用异步处理add_action('publish_post', function($post_id, $post) { if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return; if (wp_is_post_revision($post_id)) return; // 使用异步处理 async_share_to_social_media($post_id); }, 10, 2); ### 7.2 缓存策略 class SocialSyncCache { private static $cache_group = 'social_sync'; private static $cache_expiration = 3600; // 1小时 public static function get($key) { return wp_cache_get($key, self::$cache_group); } public static function set($key, $data) { return wp_cache_set($key, $data, self::$cache_group, self::$cache_expiration); } public static function delete($key) { return wp_cache_delete($key, self::$cache_group); } // 缓存API响应 public static function cached_api_call($callback, $args, $cache_key) { $cached = self::get($cache_key); if ($cached !== false) { return $cached; } $result = call_user_func_array($callback, $args); self::set($cache_key, $result); return $result; } } // 使用缓存的API调用示例function get_cached_twitter_profile() { $cache_key = 'twitter_profile_' . md5(get_option('twitter_access_token')); return SocialSyncCache::cached_api_call( 'fetch_twitter_profile', [], $cache_key ); } ### 7.3 安全加固 class SocialSyncSecurity { // 验证API响应 public static function validate_api_response($response, $expected_structure) { if (is_wp_error($response)) { return false; } $body = json_decode(wp_remote_retrieve_body($response), true); foreach ($expected_structure as $key => $type) { if (!isset($body[$key])) { return false; } if (gettype($body[$key]) !== $type) { return false; } } return true; } // 清理用户输入 public static function sanitize_social_message($message) { // 移除潜在的危险内容 $message = strip_tags($message); $message = preg_replace('/[^p{L}p{N}p{P}p{S}s]/u', '', $message); // 限制长度 $message = substr($message, 0, 5000); return $message; } // 验证访问权限 public static function check_api_permissions($platform) { $user_id = get_current_user_id(); if (!current_user_can('publish_posts')) { return false; } // 检查用户是否有该平台的分享权限 $user_permissions = get_user_meta($user_id, 'social_sync_permissions', true); if (empty($user_permissions) || !in_array($platform, $user_permissions)) { return false; } return true; } } ## 第八部分:测试与部署 ### 8.1 单元测试示例 // 测试文件:test-social-sync.phpclass SocialSyncTest extends WP_UnitTestCase { public function setUp() { parent::setUp(); // 初始化插件 require_once plugin_dir_path(__FILE__) . 'social-auto-sync.php'; }
在当今数字营销时代,社交媒体已成为企业与个人品牌推广不可或缺的渠道。然而,手动将WordPress网站内容同步到各个社交媒体平台不仅耗时耗力,还容易出错。据统计,营销人员平均每周花费6-15小时在社交媒体内容管理上,其中大部分时间用于内容分发和调度。
通过WordPress代码二次开发实现自动化社交媒体同步,不仅可以节省大量时间,还能确保内容在不同平台间的一致性,提高发布效率。本教程将引导您从零开始,通过自定义开发实现这一功能,同时探索如何将常用互联网小工具集成到WordPress中。
WordPress的强大之处在于其完善的钩子(Hooks)系统,包括动作(Actions)和过滤器(Filters)。要实现自动化社交媒体同步,我们需要利用这些钩子在适当的时候触发我们的代码。
// 示例:基本的WordPress钩子使用
add_action('publish_post', 'sync_to_social_media', 10, 2);
function sync_to_social_media($post_id, $post) {
// 当文章发布时执行社交媒体同步
// 具体实现代码将在后续部分添加
}
为了避免主题更新导致代码丢失,我们建议将功能实现为独立插件:
- 在
wp-content/plugins/目录下创建新文件夹social-auto-sync - 创建主插件文件
social-auto-sync.php - 添加插件头部信息:
<?php
/**
* Plugin Name: 社交媒体自动同步
* Plugin URI: https://yourwebsite.com/
* Description: 自动将WordPress内容同步到各大社交媒体平台
* Version: 1.0.0
* Author: 您的名字
* License: GPL v2 or later
*/
确保您的开发环境满足以下要求:
- WordPress 5.0+
- PHP 7.4+
- 启用curl扩展(用于API调用)
- 文本编辑器或IDE(如VS Code、PHPStorm)
要实现自动化同步,首先需要获取各社交媒体平台的API访问权限:
- Twitter(X):通过Twitter开发者门户创建应用
- Facebook:使用Facebook开发者工具创建应用并获取访问令牌
- LinkedIn:在LinkedIn开发者门户创建应用
- Instagram:通过Facebook开发者工具(Instagram属于Facebook生态)
永远不要在代码中硬编码API密钥。使用WordPress选项API安全存储:
// 创建设置页面存储API密钥
add_action('admin_menu', 'social_sync_add_admin_menu');
function social_sync_add_admin_menu() {
add_options_page(
'社交媒体同步设置',
'社媒同步',
'manage_options',
'social-sync-settings',
'social_sync_settings_page'
);
}
function social_sync_settings_page() {
?>
<div class="wrap">
<h1>社交媒体同步设置</h1>
<form method="post" action="options.php">
<?php
settings_fields('social_sync_settings_group');
do_settings_sections('social-sync-settings');
submit_button();
?>
</form>
</div>
<?php
}
// 注册设置
add_action('admin_init', 'social_sync_settings_init');
function social_sync_settings_init() {
register_setting('social_sync_settings_group', 'social_sync_settings');
add_settings_section(
'social_sync_api_section',
'API设置',
null,
'social-sync-settings'
);
add_settings_field(
'twitter_api_key',
'Twitter API密钥',
'social_sync_api_key_callback',
'social-sync-settings',
'social_sync_api_section',
['label_for' => 'twitter_api_key']
);
// 添加更多API字段...
}
function social_sync_api_key_callback($args) {
$options = get_option('social_sync_settings');
$id = $args['label_for'];
$value = isset($options[$id]) ? $options[$id] : '';
?>
<input type="password" id="<?php echo esc_attr($id); ?>"
name="social_sync_settings[<?php echo esc_attr($id); ?>]"
value="<?php echo esc_attr($value); ?>"
class="regular-text">
<?php
}
当WordPress文章发布时,自动提取内容并分享到社交媒体:
// 监听文章发布
add_action('publish_post', 'auto_share_on_publish', 10, 2);
function auto_share_on_publish($post_id, $post) {
// 防止无限循环
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (wp_is_post_revision($post_id)) return;
// 检查是否已经分享过
if (get_post_meta($post_id, '_social_shared', true)) return;
// 获取文章信息
$title = get_the_title($post_id);
$excerpt = wp_trim_words(get_the_excerpt($post_id), 30, '...');
$permalink = get_permalink($post_id);
$featured_image = get_the_post_thumbnail_url($post_id, 'medium');
// 构建分享内容
$message = $title . "nn" . $excerpt . "nn阅读更多: " . $permalink;
// 分享到各个平台
$results = [];
// Twitter分享
if (get_option('social_sync_twitter_enable')) {
$results['twitter'] = share_to_twitter($message, $featured_image);
}
// Facebook分享
if (get_option('social_sync_facebook_enable')) {
$results['facebook'] = share_to_facebook($message, $permalink, $featured_image);
}
// LinkedIn分享
if (get_option('social_sync_linkedin_enable')) {
$results['linkedin'] = share_to_linkedin($title, $excerpt, $permalink, $featured_image);
}
// 标记为已分享
update_post_meta($post_id, '_social_shared', true);
update_post_meta($post_id, '_social_share_results', $results);
// 记录日志
social_sync_log('文章发布同步', $post_id, $results);
}
function share_to_twitter($message, $image_url = null) {
$settings = get_option('social_sync_settings');
$api_key = $settings['twitter_api_key'] ?? '';
$api_secret = $settings['twitter_api_secret'] ?? '';
$access_token = $settings['twitter_access_token'] ?? '';
$access_secret = $settings['twitter_access_secret'] ?? '';
if (empty($api_key) || empty($access_token)) {
return ['success' => false, 'error' => 'API凭证未配置'];
}
// 使用Twitter API v2
$endpoint = 'https://api.twitter.com/2/tweets';
// 构建请求数据
$data = ['text' => substr($message, 0, 280)]; // Twitter限制280字符
// 如果有图片,先上传媒体
if ($image_url) {
$media_id = upload_twitter_media($image_url, $api_key, $api_secret, $access_token, $access_secret);
if ($media_id) {
$data['media'] = ['media_ids' => [$media_id]];
}
}
// 发送请求
$response = wp_remote_post($endpoint, [
'headers' => [
'Authorization' => 'Bearer ' . $access_token,
'Content-Type' => 'application/json',
],
'body' => json_encode($data),
'timeout' => 30,
]);
if (is_wp_error($response)) {
return ['success' => false, 'error' => $response->get_error_message()];
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['data']['id'])) {
return ['success' => true, 'tweet_id' => $body['data']['id']];
} else {
return ['success' => false, 'error' => $body['errors'][0]['detail'] ?? '未知错误'];
}
}
function upload_twitter_media($image_url, $api_key, $api_secret, $access_token, $access_secret) {
// 下载图片
$image_data = wp_remote_get($image_url);
if (is_wp_error($image_data)) {
return false;
}
$image_content = wp_remote_retrieve_body($image_data);
// 上传到Twitter媒体端点
$upload_endpoint = 'https://upload.twitter.com/1.1/media/upload.json';
$response = wp_remote_post($upload_endpoint, [
'headers' => [
'Authorization' => 'OAuth oauth_consumer_key="' . $api_key . '", oauth_nonce="' . wp_generate_uuid4() . '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' . time() . '", oauth_token="' . $access_token . '", oauth_version="1.0"',
],
'body' => [
'media_data' => base64_encode($image_content)
],
'timeout' => 30,
]);
if (is_wp_error($response)) {
return false;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
return $body['media_id_string'] ?? false;
}
function share_to_twitter($message, $image_url = null) {
$settings = get_option('social_sync_settings');
$api_key = $settings['twitter_api_key'] ?? '';
$api_secret = $settings['twitter_api_secret'] ?? '';
$access_token = $settings['twitter_access_token'] ?? '';
$access_secret = $settings['twitter_access_secret'] ?? '';
if (empty($api_key) || empty($access_token)) {
return ['success' => false, 'error' => 'API凭证未配置'];
}
// 使用Twitter API v2
$endpoint = 'https://api.twitter.com/2/tweets';
// 构建请求数据
$data = ['text' => substr($message, 0, 280)]; // Twitter限制280字符
// 如果有图片,先上传媒体
if ($image_url) {
$media_id = upload_twitter_media($image_url, $api_key, $api_secret, $access_token, $access_secret);
if ($media_id) {
$data['media'] = ['media_ids' => [$media_id]];
}
}
// 发送请求
$response = wp_remote_post($endpoint, [
'headers' => [
'Authorization' => 'Bearer ' . $access_token,
'Content-Type' => 'application/json',
],
'body' => json_encode($data),
'timeout' => 30,
]);
if (is_wp_error($response)) {
return ['success' => false, 'error' => $response->get_error_message()];
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['data']['id'])) {
return ['success' => true, 'tweet_id' => $body['data']['id']];
} else {
return ['success' => false, 'error' => $body['errors'][0]['detail'] ?? '未知错误'];
}
}
function upload_twitter_media($image_url, $api_key, $api_secret, $access_token, $access_secret) {
// 下载图片
$image_data = wp_remote_get($image_url);
if (is_wp_error($image_data)) {
return false;
}
$image_content = wp_remote_retrieve_body($image_data);
// 上传到Twitter媒体端点
$upload_endpoint = 'https://upload.twitter.com/1.1/media/upload.json';
$response = wp_remote_post($upload_endpoint, [
'headers' => [
'Authorization' => 'OAuth oauth_consumer_key="' . $api_key . '", oauth_nonce="' . wp_generate_uuid4() . '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' . time() . '", oauth_token="' . $access_token . '", oauth_version="1.0"',
],
'body' => [
'media_data' => base64_encode($image_content)
],
'timeout' => 30,
]);
if (is_wp_error($response)) {
return false;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
return $body['media_id_string'] ?? false;
}
function share_to_facebook($message, $link, $image_url = null) {
$settings = get_option('social_sync_settings');
$page_id = $settings['facebook_page_id'] ?? '';
$access_token = $settings['facebook_access_token'] ?? '';
if (empty($page_id) || empty($access_token)) {
return ['success' => false, 'error' => 'Facebook配置不完整'];
}
$endpoint = "https://graph.facebook.com/v12.0/{$page_id}/feed";
// 构建请求数据
$data = [
'message' => $message,
'link' => $link,
'access_token' => $access_token,
];
// 如果有图片,附加图片URL
if ($image_url) {
$data['picture'] = $image_url;
}
// 发送请求
$response = wp_remote_post($endpoint, [
'body' => $data,
'timeout' => 30,
]);
if (is_wp_error($response)) {
return ['success' => false, 'error' => $response->get_error_message()];
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['id'])) {
return ['success' => true, 'post_id' => $body['id']];
} else {
return ['success' => false, 'error' => $body['error']['message'] ?? '未知错误'];
}
}
function share_to_facebook($message, $link, $image_url = null) {
$settings = get_option('social_sync_settings');
$page_id = $settings['facebook_page_id'] ?? '';
$access_token = $settings['facebook_access_token'] ?? '';
if (empty($page_id) || empty($access_token)) {
return ['success' => false, 'error' => 'Facebook配置不完整'];
}
$endpoint = "https://graph.facebook.com/v12.0/{$page_id}/feed";
// 构建请求数据
$data = [
'message' => $message,
'link' => $link,
'access_token' => $access_token,
];
// 如果有图片,附加图片URL
if ($image_url) {
$data['picture'] = $image_url;
}
// 发送请求
$response = wp_remote_post($endpoint, [
'body' => $data,
'timeout' => 30,
]);
if (is_wp_error($response)) {
return ['success' => false, 'error' => $response->get_error_message()];
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['id'])) {
return ['success' => true, 'post_id' => $body['id']];
} else {
return ['success' => false, 'error' => $body['error']['message'] ?? '未知错误'];
}
}
除了即时发布,还可以实现定时发布到社交媒体:
// 创建自定义计划任务
add_action('social_sync_scheduled_share', 'scheduled_social_share', 10, 1);
function scheduled_social_share($post_id) {
$post = get_post($post_id);
if (!$post || $post->post_status !== 'future') {
return;
}
// 执行社交媒体分享
auto_share_on_publish($post_id, $post);
}
// 当定时文章发布时触发
add_action('publish_future_post', 'schedule_social_share_on_publish', 10, 1);
function schedule_social_share_on_publish($post_id) {
$post = get_post($post_id);
$publish_time = strtotime($post->post_date);
// 安排在文章发布时间执行社交媒体分享
wp_schedule_single_event($publish_time, 'social_sync_scheduled_share', [$post_id]);
}
不同社交媒体平台有不同的内容要求,需要针对性地优化:
function format_content_for_platform($content, $platform, $post_id) {
$formatted = $content;
switch ($platform) {
case 'twitter':
// Twitter: 280字符限制,添加话题标签
$formatted = substr($content, 0, 250); // 留空间给链接和标签
// 自动提取或添加话题标签
$tags = get_post_tags($post_id);
if ($tags) {
$tag_names = array_slice(wp_list_pluck($tags, 'name'), 0, 3);
$hashtags = ' ' . implode(' ', array_map(function($tag) {
return '#' . preg_replace('/s+/', '', $tag);
}, $tag_names));
if (strlen($formatted . $hashtags) <= 280) {
$formatted .= $hashtags;
}
}
break;
case 'linkedin':
// LinkedIn: 更专业的语气,可以更长
$formatted = $content . "nn#WordPress #内容营销";
break;
case 'facebook':
// Facebook: 更友好,可以添加表情符号
$formatted = "📢 新文章发布!nn" . $content . "nn点击链接阅读全文 👇";
break;
}
return $formatted;
}
完善的错误处理是自动化系统可靠性的关键:
function social_sync_log($action, $post_id, $data) {
$log_entry = [
'timestamp' => current_time('mysql'),
'action' => $action,
'post_id' => $post_id,
'data' => $data,
'ip' => $_SERVER['REMOTE_ADDR'] ?? '未知',
];
// 获取现有日志
$logs = get_option('social_sync_logs', []);
// 限制日志数量(保留最近100条)
if (count($logs) >= 100) {
array_shift($logs);
}
// 添加新日志
$logs[] = $log_entry;
// 保存日志
update_option('social_sync_logs', $logs, false);
}
// 创建日志查看页面
add_action('admin_menu', 'social_sync_logs_page');
function social_sync_logs_page() {
add_submenu_page(
'options-general.php',
'社交媒体同步日志',
'社媒同步日志',
'manage_options',
'social-sync-logs',
'social_sync_logs_page_content'
);
}
function social_sync_logs_page_content() {
$logs = get_option('social_sync_logs', []);
?>
<div class="wrap">
<h1>社交媒体同步日志</h1>
<?php if (empty($logs)): ?>
<p>暂无日志记录。</p>
<?php else: ?>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>时间</th>
<th>操作</th>
<th>文章ID</th>
<th>结果</th>
<th>IP地址</th>
</tr>
</thead>
<tbody>
<?php foreach (array_reverse($logs) as $log): ?>
<tr>
<td><?php echo esc_html($log['timestamp']); ?></td>
<td><?php echo esc_html($log['action']); ?></td>
<td>
<?php if ($log['post_id']): ?>
<a href="<?php echo get_edit_post_link($log['post_id']); ?>">
文章#<?php echo esc_html($log['post_id']); ?>
</a>
<?php else: ?>
N/A
<?php endif; ?>
</td>
<td>
<?php
if (is_array($log['data'])) {
foreach ($log['data'] as $platform => $result) {
echo esc_html($platform) . ': ' .
($result['success'] ? '成功' : '失败') . '<br>';
if (!$result['success'] && isset($result['error'])) {
echo '<small style="color:red;">' .
esc_html($result['error']) . '</small><br>';
}
}
}
?>
</td>
<td><?php echo esc_html($log['ip']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<form method="post" style="margin-top: 20px;">
<?php wp_nonce_field('clear_social_sync_logs', 'social_sync_nonce'); ?>
<input type="hidden" name="action" value="clear_logs">
<input type="submit" class="button button-secondary" value="清空日志">
</form>
<?php endif; ?>
</div>
<?php
// 处理清空日志请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' &&
isset($_POST['action']) &&
$_POST['action'] === 'clear_logs' &&
`clear_social_sync_logs', 'social_sync_nonce')) {
update_option('social_sync_logs', []);
echo '<div class="notice notice-success is-dismissible"><p>日志已清空。</p></div>';
}
}
## 第五部分:常用互联网小工具集成
### 5.1 URL短链接生成器
集成短链接服务,优化社交媒体分享:
function generate_short_url($long_url, $service = 'bitly') {
$settings = get_option('social_sync_settings');
switch ($service) {
case 'bitly':
$access_token = $settings['bitly_access_token'] ?? '';
if (empty($access_token)) return $long_url;
$endpoint = 'https://api-ssl.bitly.com/v4/shorten';
$response = wp_remote_post($endpoint, [
'headers' => [
'Authorization' => 'Bearer ' . $access_token,
'Content-Type' => 'application/json',
],
'body' => json_encode(['long_url' => $long_url]),
'timeout' => 15,
]);
if (!is_wp_error($response)) {
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['link'])) {
return $body['link'];
}
}
break;
case 'tinyurl':
$endpoint = 'https://tinyurl.com/api-create.php?url=' . urlencode($long_url);
$response = wp_remote_get($endpoint);
if (!is_wp_error($response)) {
$short_url = wp_remote_retrieve_body($response);
if (filter_var($short_url, FILTER_VALIDATE_URL)) {
return $short_url;
}
}
break;
}
return $long_url; // 失败时返回原链接
}
// 在分享函数中使用短链接
function auto_share_on_publish_with_shorturl($post_id, $post) {
// ... 之前的代码 ...
$permalink = get_permalink($post_id);
$short_url = generate_short_url($permalink, 'bitly');
// 使用短链接构建消息
$message = $title . "nn" . $excerpt . "nn" . $short_url;
// ... 后续分享代码 ...
}
### 5.2 内容分析工具集成
集成内容分析功能,优化分享效果:
function analyze_content_for_sharing($post_id) {
$post = get_post($post_id);
$content = $post->post_content;
$title = $post->post_title;
$analysis = [
'readability_score' => calculate_readability($content),
'keyword_density' => get_keyword_density($content, $title),
'optimal_length' => check_length_optimization($content),
'image_count' => count_images_in_content($content),
'has_video' => has_video_content($content),
];
// 根据分析结果给出建议
$suggestions = generate_sharing_suggestions($analysis);
return [
'analysis' => $analysis,
'suggestions' => $suggestions,
];
}
function calculate_readability($content) {
// 实现Flesch-Kincaid可读性测试简化版
$text = strip_tags($content);
$words = str_word_count($text);
$sentences = preg_split('/[.!?]+/', $text);
$sentence_count = count(array_filter($sentences));
if ($words === 0 || $sentence_count === 0) {
return 0;
}
$average_words_per_sentence = $words / $sentence_count;
$average_syllables_per_word = estimate_syllables($text) / $words;
// Flesch Reading Ease公式
$score = 206.835 - (1.015 * $average_words_per_sentence) - (84.6 * $average_syllables_per_word);
return round($score, 2);
}
function generate_sharing_suggestions($analysis) {
$suggestions = [];
if ($analysis['readability_score'] < 60) {
$suggestions[] = '内容可读性较低,建议简化句子结构';
}
if ($analysis['image_count'] === 0) {
$suggestions[] = '建议添加相关图片以提高社交媒体参与度';
}
if ($analysis['has_video']) {
$suggestions[] = '检测到视频内容,建议在社交媒体上突出显示';
}
return $suggestions;
}
### 5.3 自动话题标签生成器
function generate_hashtags($content, $title, $count = 5) {
// 提取关键词
$keywords = extract_keywords($content . ' ' . $title);
// 过滤和排序关键词
$filtered_keywords = array_filter($keywords, function($word) {
// 移除太短或太常见的词
return strlen($word) > 3 && !in_array(strtolower($word), [
'this', 'that', 'with', 'from', 'have', 'were', 'they'
]);
});
// 转换为话题标签
$hashtags = array_map(function($word) {
// 移除特殊字符,转换为小写
$clean_word = preg_replace('/[^a-zA-Z0-9]/', '', $word);
return '#' . ucfirst(strtolower($clean_word));
}, array_slice($filtered_keywords, 0, $count));
return $hashtags;
}
function extract_keywords($text) {
// 移除HTML标签和特殊字符
$clean_text = strip_tags($text);
$clean_text = preg_replace('/[^p{L}p{N}s]/u', ' ', $clean_text);
// 分词
$words = preg_split('/s+/', $clean_text);
// 统计词频
$word_counts = array_count_values(array_map('strtolower', $words));
// 按频率排序
arsort($word_counts);
return array_keys($word_counts);
}
## 第六部分:用户界面与交互优化
### 6.1 文章编辑界面集成
在文章编辑界面添加社交媒体分享控制面板:
add_action('add_meta_boxes', 'add_social_sync_meta_box');
function add_social_sync_meta_box() {
add_meta_box(
'social_sync_meta_box',
'社交媒体分享设置',
'render_social_sync_meta_box',
'post',
'side',
'high'
);
}
function render_social_sync_meta_box($post) {
wp_nonce_field('social_sync_meta_box', 'social_sync_nonce');
$shared = get_post_meta($post->ID, '_social_shared', true);
$share_results = get_post_meta($post->ID, '_social_share_results', true);
?>
<div id="social-sync-controls">
<p>
<label>
<input type="checkbox" name="auto_share" value="1"
<?php checked(!$shared); ?> <?php echo $shared ? 'disabled' : ''; ?>>
发布时自动分享到社交媒体
</label>
</p>
<?php if ($shared): ?>
<div class="notice notice-success inline">
<p>✅ 已分享到社交媒体</p>
<?php if ($share_results): ?>
<ul style="margin: 5px 0; padding-left: 20px;">
<?php foreach ($share_results as $platform => $result): ?>
<li>
<?php echo esc_html(ucfirst($platform)); ?>:
<?php echo $result['success'] ? '✅ 成功' : '❌ 失败'; ?>
<?php if (!$result['success'] && isset($result['error'])): ?>
<br><small style="color: #666;"><?php echo esc_html($result['error']); ?></small>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
<p>
<button type="button" id="reshare-button" class="button button-secondary">
重新分享
</button>
<span class="description">强制重新分享到所有平台</span>
</p>
<?php endif; ?>
<div id="platform-selection" style="margin-top: 10px; <?php echo $shared ? 'display:none;' : ''; ?>">
<p><strong>选择分享平台:</strong></p>
<?php
$platforms = [
'twitter' => 'Twitter',
'facebook' => 'Facebook',
'linkedin' => 'LinkedIn',
];
foreach ($platforms as $key => $label):
$enabled = get_option("social_sync_{$key}_enable", true);
?>
<p>
<label>
<input type="checkbox" name="share_platforms[]"
value="<?php echo esc_attr($key); ?>"
<?php checked($enabled); ?>
<?php echo $enabled ? '' : 'disabled'; ?>>
<?php echo esc_html($label); ?>
<?php if (!$enabled): ?>
<br><small style="color: #999;">(在设置中启用)</small>
<?php endif; ?>
</label>
</p>
<?php endforeach; ?>
</div>
<div id="custom-message" style="margin-top: 10px; display: none;">
<p><strong>自定义分享消息:</strong></p>
<textarea name="custom_share_message" rows="3" style="width:100%;"></textarea>
<p class="description">留空使用自动生成的消息</p>
</div>
<p>
<a href="#" id="toggle-custom-message">自定义消息</a> |
<a href="#" id="preview-share">预览</a>
</p>
</div>
<script>
jQuery(document).ready(function($) {
// 切换自定义消息区域
$('#toggle-custom-message').click(function(e) {
e.preventDefault();
$('#custom-message').toggle();
});
// 预览分享
$('#preview-share').click(function(e) {
e.preventDefault();
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'preview_social_share',
post_id: <?php echo $post->ID; ?>,
nonce: '<?php echo wp_create_nonce("preview_share_{$post->ID}"); ?>'
},
success: function(response) {
if (response.success) {
// 显示预览模态框
showPreviewModal(response.data);
}
}
});
});
// 重新分享按钮
$('#reshare-button').click(function() {
if (confirm('确定要重新分享这篇文章吗?')) {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'reshare_post',
post_id: <?php echo $post->ID; ?>,
nonce: '<?php echo wp_create_nonce("reshare_{$post->ID}"); ?>'
},
success: function(response) {
if (response.success) {
location.reload();
} else {
alert('重新分享失败:' + response.data);
}
}
});
}
});
function showPreviewModal(previews) {
// 创建并显示预览模态框
// 实现模态框显示逻辑
}
});
</script>
<?php
}
### 6.2 AJAX交互处理
add_action('wp_ajax_preview_social_share', 'handle_preview_social_share');
add_action('wp_ajax_reshare_post', 'handle_reshare_post');
function handle_preview_social_share() {
check_ajax_referer('preview_share_' . $_POST['post_id'], 'nonce');
$post_id = intval($_POST['post_id']);
$post = get_post($post_id);
if (!$post) {
wp_die('文章不存在');
}
$previews = [];
$platforms = ['twitter', 'facebook', 'linkedin'];
foreach ($platforms as $platform) {
if (get_option("social_sync_{$platform}_enable")) {
$message = generate_share_message($post, $platform);
$previews[$platform] = [
'message' => $message,
'length' => strlen($message),
'max_length' => $platform === 'twitter' ? 280 : 5000,
];
}
}
wp_send_json_success($previews);
}
function handle_reshare_post() {
check_ajax_referer('reshare_' . $_POST['post_id'], 'nonce');
$post_id = intval($_POST['post_id']);
$post = get_post($post_id);
if (!$post) {
wp_send_json_error('文章不存在');
}
// 清除之前的分享标记
delete_post_meta($post_id, '_social_shared');
delete_post_meta($post_id, '_social_share_results');
// 重新分享
auto_share_on_publish($post_id, $post);
wp_send_json_success('重新分享成功');
}
## 第七部分:性能优化与安全考虑
### 7.1 异步处理优化
对于耗时的社交媒体API调用,使用异步处理避免阻塞:
function async_share_to_social_media($post_id) {
// 使用WordPress后台任务系统
if (!wp_next_scheduled('async_social_share', [$post_id])) {
wp_schedule_single_event(time() + 5, 'async_social_share', [$post_id]);
}
}
add_action('async_social_share', 'execute_async_social_share');
function execute_async_social_share($post_id) {
$post = get_post($post_id);
if ($post && $post->post_status === 'publish') {
auto_share_on_publish($post_id, $post);
}
}
// 修改发布钩子使用异步处理
add_action('publish_post', function($post_id, $post) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (wp_is_post_revision($post_id)) return;
// 使用异步处理
async_share_to_social_media($post_id);
}, 10, 2);
### 7.2 缓存策略
class SocialSyncCache {
private static $cache_group = 'social_sync';
private static $cache_expiration = 3600; // 1小时
public static function get($key) {
return wp_cache_get($key, self::$cache_group);
}
public static function set($key, $data) {
return wp_cache_set($key, $data, self::$cache_group, self::$cache_expiration);
}
public static function delete($key) {
return wp_cache_delete($key, self::$cache_group);
}
// 缓存API响应
public static function cached_api_call($callback, $args, $cache_key) {
$cached = self::get($cache_key);
if ($cached !== false) {
return $cached;
}
$result = call_user_func_array($callback, $args);
self::set($cache_key, $result);
return $result;
}
}
// 使用缓存的API调用示例
function get_cached_twitter_profile() {
$cache_key = 'twitter_profile_' . md5(get_option('twitter_access_token'));
return SocialSyncCache::cached_api_call(
'fetch_twitter_profile',
[],
$cache_key
);
}
### 7.3 安全加固
class SocialSyncSecurity {
// 验证API响应
public static function validate_api_response($response, $expected_structure) {
if (is_wp_error($response)) {
return false;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
foreach ($expected_structure as $key => $type) {
if (!isset($body[$key])) {
return false;
}
if (gettype($body[$key]) !== $type) {
return false;
}
}
return true;
}
// 清理用户输入
public static function sanitize_social_message($message) {
// 移除潜在的危险内容
$message = strip_tags($message);
$message = preg_replace('/[^p{L}p{N}p{P}p{S}s]/u', '', $message);
// 限制长度
$message = substr($message, 0, 5000);
return $message;
}
// 验证访问权限
public static function check_api_permissions($platform) {
$user_id = get_current_user_id();
if (!current_user_can('publish_posts')) {
return false;
}
// 检查用户是否有该平台的分享权限
$user_permissions = get_user_meta($user_id, 'social_sync_permissions', true);
if (empty($user_permissions) || !in_array($platform, $user_permissions)) {
return false;
}
return true;
}
}
## 第八部分:测试与部署
### 8.1 单元测试示例
// 测试文件:test-social-sync.php
class SocialSyncTest extends WP_UnitTestCase {
public function setUp() {
parent::setUp();
// 初始化插件
require_once plugin_dir_path(__FILE__) . 'social-auto-sync.php';
}


