文章目录[隐藏]
WordPress插件开发教程:实现网站内容自动同步到社交媒体
引言:为什么需要内容自动同步功能
在当今数字化时代,社交媒体已成为网站流量和用户互动的重要来源。根据最新统计,超过70%的网络用户通过社交媒体发现新内容,而拥有自动同步功能的网站其社交媒体互动率平均提高45%。对于WordPress网站管理员而言,每次发布新内容后手动分享到各个社交平台不仅耗时耗力,而且容易遗漏,影响内容传播效果。
本教程将详细讲解如何开发一个WordPress插件,实现网站内容自动同步到主流社交媒体平台(如Twitter、Facebook、LinkedIn等)。通过这个实战项目,您不仅能掌握WordPress插件开发的核心技术,还能学习如何通过代码二次开发实现实用的互联网小工具功能。
第一章:WordPress插件开发基础
1.1 WordPress插件架构概述
WordPress插件本质上是一组PHP文件,遵循特定的结构和命名规范,用于扩展WordPress核心功能。一个标准的WordPress插件至少包含:
- 主文件:包含插件元信息的PHP文件
- 功能文件:实现插件核心逻辑的PHP文件
- 资源文件:CSS、JavaScript和图像等资源
- 语言文件:用于国际化的翻译文件
1.2 创建插件基本结构
首先,在WordPress的wp-content/plugins/目录下创建一个新文件夹,命名为auto-social-sync。在该文件夹中创建以下文件结构:
auto-social-sync/
├── auto-social-sync.php # 插件主文件
├── includes/
│ ├── class-social-api.php # 社交媒体API处理类
│ ├── class-post-handler.php # 文章处理类
│ └── class-admin-settings.php # 管理设置类
├── admin/
│ ├── css/
│ │ └── admin-style.css # 管理界面样式
│ └── js/
│ └── admin-script.js # 管理界面脚本
├── public/
│ ├── css/
│ │ └── public-style.css # 前端样式
│ └── js/
│ └── public-script.js # 前端脚本
└── languages/
└── auto-social-sync.pot # 翻译模板文件
1.3 编写插件主文件
插件主文件是插件的入口点,需要包含标准的插件头部信息:
<?php
/**
* Plugin Name: Auto Social Sync
* Plugin URI: https://yourwebsite.com/auto-social-sync
* Description: 自动将WordPress内容同步到社交媒体平台
* Version: 1.0.0
* Author: 您的姓名
* Author URI: https://yourwebsite.com
* License: GPL v2 or later
* Text Domain: auto-social-sync
* Domain Path: /languages
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('ASS_VERSION', '1.0.0');
define('ASS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('ASS_PLUGIN_URL', plugin_dir_url(__FILE__));
define('ASS_PLUGIN_BASENAME', plugin_basename(__FILE__));
// 加载必要文件
require_once ASS_PLUGIN_DIR . 'includes/class-social-api.php';
require_once ASS_PLUGIN_DIR . 'includes/class-post-handler.php';
require_once ASS_PLUGIN_DIR . 'includes/class-admin-settings.php';
// 初始化插件
function ass_init_plugin() {
// 检查WordPress版本
if (version_compare(get_bloginfo('version'), '5.0', '<')) {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>';
echo __('Auto Social Sync需要WordPress 5.0或更高版本。', 'auto-social-sync');
echo '</p></div>';
});
return;
}
// 初始化各个组件
$social_api = new ASS_Social_API();
$post_handler = new ASS_Post_Handler($social_api);
$admin_settings = new ASS_Admin_Settings($social_api);
// 注册激活和停用钩子
register_activation_hook(__FILE__, array($admin_settings, 'activate_plugin'));
register_deactivation_hook(__FILE__, array($admin_settings, 'deactivate_plugin'));
}
add_action('plugins_loaded', 'ass_init_plugin');
第二章:社交媒体API集成
2.1 设计API抽象层
为了支持多个社交媒体平台,我们需要设计一个灵活的API抽象层。首先创建社交媒体API基类:
<?php
// includes/class-social-api.php
class ASS_Social_API {
protected $platforms = array();
protected $options = array();
public function __construct() {
$this->options = get_option('ass_settings', array());
$this->register_platforms();
}
// 注册支持的社交媒体平台
protected function register_platforms() {
// 默认支持的平台
$this->platforms = array(
'twitter' => array(
'name' => 'Twitter',
'class' => 'ASS_Twitter_API',
'enabled' => false,
'auth_url' => ''
),
'facebook' => array(
'name' => 'Facebook',
'class' => 'ASS_Facebook_API',
'enabled' => false,
'auth_url' => ''
),
'linkedin' => array(
'name' => 'LinkedIn',
'class' => 'ASS_LinkedIn_API',
'enabled' => false,
'auth_url' => ''
)
);
// 允许其他插件添加更多平台
$this->platforms = apply_filters('ass_register_platforms', $this->platforms);
}
// 获取所有平台
public function get_platforms() {
return $this->platforms;
}
// 获取特定平台
public function get_platform($platform_id) {
return isset($this->platforms[$platform_id]) ? $this->platforms[$platform_id] : false;
}
// 发布内容到所有已启用的平台
public function publish_to_all($post_id, $message = '') {
$results = array();
foreach ($this->platforms as $platform_id => $platform) {
if ($this->is_platform_enabled($platform_id)) {
$result = $this->publish_to_platform($platform_id, $post_id, $message);
$results[$platform_id] = $result;
}
}
return $results;
}
// 发布内容到特定平台
public function publish_to_platform($platform_id, $post_id, $message = '') {
$platform = $this->get_platform($platform_id);
if (!$platform || !$this->is_platform_enabled($platform_id)) {
return new WP_Error('platform_disabled', sprintf(__('%s平台未启用或未配置', 'auto-social-sync'), $platform['name']));
}
// 动态加载平台类
$class_name = $platform['class'];
if (!class_exists($class_name)) {
$file_path = ASS_PLUGIN_DIR . 'includes/platforms/class-' . strtolower(str_replace('_', '-', $platform_id)) . '-api.php';
if (file_exists($file_path)) {
require_once $file_path;
}
}
if (class_exists($class_name)) {
$api_instance = new $class_name($this->options);
return $api_instance->publish($post_id, $message);
}
return new WP_Error('class_not_found', sprintf(__('找不到%s平台的API类', 'auto-social-sync'), $platform['name']));
}
// 检查平台是否启用
public function is_platform_enabled($platform_id) {
$platform = $this->get_platform($platform_id);
if (!$platform) {
return false;
}
// 检查全局设置
if (isset($this->options['platforms'][$platform_id]['enabled'])) {
return (bool) $this->options['platforms'][$platform_id]['enabled'];
}
return $platform['enabled'];
}
}
2.2 实现Twitter API集成
接下来,我们实现Twitter API的具体集成。首先需要在Twitter开发者平台创建应用并获取API密钥。
<?php
// includes/platforms/class-twitter-api.php
class ASS_Twitter_API {
private $consumer_key;
private $consumer_secret;
private $access_token;
private $access_token_secret;
private $api_url = 'https://api.twitter.com/2/';
public function __construct($options) {
$twitter_settings = isset($options['twitter']) ? $options['twitter'] : array();
$this->consumer_key = isset($twitter_settings['consumer_key']) ? $twitter_settings['consumer_key'] : '';
$this->consumer_secret = isset($twitter_settings['consumer_secret']) ? $twitter_settings['consumer_secret'] : '';
$this->access_token = isset($twitter_settings['access_token']) ? $twitter_settings['access_token'] : '';
$this->access_token_secret = isset($twitter_settings['access_token_secret']) ? $twitter_settings['access_token_secret'] : '';
}
// 发布推文
public function publish($post_id, $message = '') {
// 验证配置
if (!$this->validate_config()) {
return new WP_Error('twitter_config_error', __('Twitter API配置不完整', 'auto-social-sync'));
}
// 获取文章信息
$post = get_post($post_id);
if (!$post) {
return new WP_Error('post_not_found', __('文章不存在', 'auto-social-sync'));
}
// 准备推文内容
$tweet_content = $this->prepare_tweet_content($post, $message);
// 检查内容长度(Twitter限制为280字符)
if (mb_strlen($tweet_content) > 280) {
$tweet_content = mb_substr($tweet_content, 0, 277) . '...';
}
// 获取文章特色图片
$media_id = $this->upload_media($post_id);
// 发布推文
$result = $this->post_tweet($tweet_content, $media_id);
if ($result && !is_wp_error($result)) {
// 记录发布日志
$this->log_activity($post_id, 'twitter', $result->data->id, $tweet_content);
return $result;
}
return $result;
}
// 准备推文内容
private function prepare_tweet_content($post, $custom_message = '') {
if (!empty($custom_message)) {
$content = $custom_message;
} else {
// 使用文章标题和链接
$title = get_the_title($post);
$permalink = get_permalink($post);
// 添加话题标签
$hashtags = $this->get_hashtags($post);
$content = $title . ' ' . $permalink;
if (!empty($hashtags)) {
$content .= ' ' . $hashtags;
}
}
return apply_filters('ass_twitter_content', $content, $post, $custom_message);
}
// 获取话题标签
private function get_hashtags($post) {
$hashtags = array();
// 从文章标签中获取
$post_tags = get_the_tags($post->ID);
if ($post_tags) {
foreach ($post_tags as $tag) {
$hashtags[] = '#' . str_replace(' ', '', $tag->name);
}
}
// 限制标签数量
$hashtags = array_slice($hashtags, 0, 3);
return implode(' ', $hashtags);
}
// 上传媒体文件
private function upload_media($post_id) {
$image_url = get_the_post_thumbnail_url($post_id, 'medium');
if (!$image_url) {
return null;
}
// 下载图片到临时文件
$tmp_file = download_url($image_url);
if (is_wp_error($tmp_file)) {
return null;
}
// 准备OAuth请求
$oauth = array(
'oauth_consumer_key' => $this->consumer_key,
'oauth_nonce' => wp_generate_password(32, false),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $this->access_token,
'oauth_version' => '1.0'
);
// 这里简化处理,实际需要完整实现Twitter媒体上传API
// 由于篇幅限制,省略详细实现
// 清理临时文件
@unlink($tmp_file);
return null; // 返回媒体ID,这里简化处理
}
// 发布推文
private function post_tweet($content, $media_id = null) {
$endpoint = $this->api_url . 'tweets';
$data = array(
'text' => $content
);
if ($media_id) {
$data['media'] = array('media_ids' => array($media_id));
}
// 使用WordPress HTTP API发送请求
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => $this->generate_oauth_header('POST', $endpoint),
'Content-Type' => 'application/json'
),
'body' => json_encode($data),
'timeout' => 30
);
$response = wp_remote_post($endpoint, $args);
if (is_wp_error($response)) {
return $response;
}
$body = json_decode(wp_remote_retrieve_body($response));
if (isset($body->errors)) {
return new WP_Error('twitter_api_error', $body->errors[0]->message);
}
return $body;
}
// 生成OAuth签名
private function generate_oauth_header($method, $url, $params = array()) {
// OAuth 1.0签名生成
// 由于篇幅限制,这里简化处理
// 实际开发中需要使用完整的OAuth 1.0实现
return 'OAuth oauth_consumer_key="' . $this->consumer_key . '", oauth_nonce="' . wp_generate_password(32, false) . '", oauth_signature="placeholder", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' . time() . '", oauth_token="' . $this->access_token . '", oauth_version="1.0"';
}
// 验证配置
private function validate_config() {
return !empty($this->consumer_key) &&
!empty($this->consumer_secret) &&
!empty($this->access_token) &&
!empty($this->access_token_secret);
}
// 记录活动日志
private function log_activity($post_id, $platform, $platform_post_id, $content) {
$logs = get_post_meta($post_id, '_ass_social_logs', true);
if (!is_array($logs)) {
$logs = array();
}
$logs[] = array(
'platform' => $platform,
'platform_post_id' => $platform_post_id,
'content' => $content,
'timestamp' => current_time('mysql'),
'status' => 'success'
);
update_post_meta($post_id, '_ass_social_logs', $logs);
}
}
第三章:文章发布处理机制
3.1 监听文章发布事件
WordPress提供了多种钩子(hooks)来监听文章状态变化。我们将利用这些钩子自动触发社交媒体同步。
<?php
// includes/class-post-handler.php
class ASS_Post_Handler {
private $social_api;
private $options;
public function __construct($social_api) {
$this->social_api = $social_api;
$this->options = get_option('ass_settings', array());
$this->init_hooks();
}
// 初始化钩子
private function init_hooks() {
// 发布新文章时触发
add_action('publish_post', array($this, 'on_post_published'), 10, 2);
// 更新已发布文章时触发
add_action('post_updated', array($this, 'on_post_updated'), 10, 3);
// 定时发布文章时触发
add_action('future_to_publish', array($this, 'on_scheduled_publish'), 10, 1);
// 文章状态变化时触发
add_action('transition_post_status', array($this, 'on_post_status_change'), 10, 3);
// 添加快捷发布按钮
add_action('post_submitbox_misc_actions', array($this, 'add_publish_actions'));
// 处理手动发布请求
add_action('admin_post_ass_manual_sync', array($this, 'handle_manual_sync'));
}
// 文章发布时处理
public function on_post_published($post_id, $post) {
// 检查是否自动发布
$auto_publish = isset($this->options['auto_publish']) ? $this->options['auto_publish'] : true;
if (!$auto_publish) {
return;
}
// 检查文章类型
$allowed_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post');
if (!in_array($post->post_type, $allowed_types)) {
return;
}
// 检查是否已发布过
if (get_post_meta($post_id, '_ass_published', true)) {
return;
}
// 检查排除条件
if ($this->is_excluded($post_id)) {
return;
}
// 准备发布内容
$message = $this->prepare_social_message($post);
// 发布到社交媒体
$results = $this->social_api->publish_to_all($post_id, $message);
// 标记为已发布
update_post_meta($post_id, '_ass_published', current_time('mysql'));
// 保存发布结果
update_post_meta($post_id, '_ass_publish_results', $results);
// 发送通知
$this->send_notification($post_id, $results);
}
// 文章更新时处理
public function on_post_updated($post_id, $post_after, $post_before) {
// 检查是否启用更新同步
$sync_updates = isset($this->options['sync_updates']) ? $this->options['sync_updates'] : false;
if (!$sync_updates || $post_after->post_status !== 'publish') {
return;
}
// 检查文章类型
$allowed_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post');
if (!in_array($post_after->post_type, $allowed_types)) {
return;
}
// 检查是否有重要更改
if (!$this->has_significant_changes($post_after, $post_before)) {
return;
}
// 准备更新消息
$message = $this->prepare_update_message($post_after);
// 发布更新
$results = $this->social_api->publish_to_all($post_id, $message);
// 记录更新发布
update_post_meta($post_id, '_ass_updated', current_time('mysql'));
update_post_meta($post_id, '_ass_update_results', $results);
}
// 定时发布处理
public function on_scheduled_publish($post) {
$this->on_post_published($post->ID, $post);
}
// 文章状态变化处理
public function on_post_status_change($new_status, $old_status, $post) {
// 从草稿或待审核状态发布时
if ($new_status === 'publish' && in_array($old_status, array('draft', 'pending'))) {
// 添加短暂延迟,确保其他元数据已保存
wp_schedule_single_event(time() + 5, 'ass_delayed_publish', array($post->ID));
}
}
// 准备社交媒体消息
private function prepare_social_message($post) {
$message_template = isset($this->options['message_template']) ?
$this->options['message_template'] :
'{title} {url} {hashtags}';
// 获取替换变量
$replacements = array(
'{title}' => get_the_title($post),
'{url}' => get_permalink($post),
'{excerpt}' => $this->get_excerpt($post),
'{author}' => get_the_author_meta('display_name', $post->post_author),
'{site_name}' => get_bloginfo('name'),
'{hashtags}' => $this->generate_hashtags($post),
'{date}' => get_the_date('', $post),
'{categories}' => $this->get_categories_list($post)
);
// 应用过滤器允许自定义变量
$replacements = apply_filters('ass_message_replacements', $replacements, $post);
// 执行替换
$message = str_replace(
array_keys($replacements),
array_values($replacements),
$message_template
);
// 清理多余空格
$message = preg_replace('/s+/', ' ', trim($message));
return apply_filters('ass_final_message', $message, $post);
}
// 获取文章摘要
private function get_excerpt($post, $length = 100) {
if (!empty($post->post_excerpt)) {
$excerpt = $post->post_excerpt;
} else {
$excerpt = strip_shortcodes($post->post_content);
$excerpt = wp_strip_all_tags($excerpt);
}
if (mb_strlen($excerpt) > $length) {
$excerpt = mb_substr($excerpt, 0, $length) . '...';
}
return $excerpt;
}
// 生成话题标签
private function generate_hashtags($post) {
$hashtags = array();
// 从文章标签获取
$post_tags = get_the_tags($post->ID);
if ($post_tags) {
foreach ($post_tags as $tag) {
$hashtag = '#' . preg_replace('/s+/', '', $tag->name);
if (mb_strlen($hashtag) <= 20) { // 避免过长的标签
$hashtags[] = $hashtag;
}
}
}
// 从分类获取
$categories = get_the_category($post->ID);
if ($categories) {
foreach ($categories as $category) {
if ($category->parent == 0) { // 只使用顶级分类
$hashtag = '#' . preg_replace('/s+/', '', $category->name);
if (!in_array($hashtag, $hashtags) && mb_strlen($hashtag) <= 20) {
$hashtags[] = $hashtag;
}
}
}
}
// 限制标签数量
$max_hashtags = isset($this->options['max_hashtags']) ? $this->options['max_hashtags'] : 3;
$hashtags = array_slice($hashtags, 0, $max_hashtags);
return implode(' ', $hashtags);
}
// 获取分类列表
private function get_categories_list($post) {
$categories = get_the_category($post->ID);
if (!$categories) {
return '';
}
$category_names = array();
foreach ($categories as $category) {
$category_names[] = $category->name;
}
return implode(', ', $category_names);
}
// 检查是否有重要更改
private function has_significant_changes($post_after, $post_before) {
// 检查标题是否更改
if ($post_after->post_title !== $post_before->post_title) {
return true;
}
// 检查内容是否显著更改(变化超过20%)
$similarity = 0;
similar_text(
strip_tags($post_after->post_content),
strip_tags($post_before->post_content),
$similarity
);
if ($similarity < 80) {
return true;
}
// 检查特色图片是否更改
$old_thumbnail = get_post_thumbnail_id($post_before->ID);
$new_thumbnail = get_post_thumbnail_id($post_after->ID);
if ($old_thumbnail !== $new_thumbnail) {
return true;
}
return false;
}
// 准备更新消息
private function prepare_update_message($post) {
$template = isset($this->options['update_template']) ?
$this->options['update_template'] :
'更新: {title} {url}';
$replacements = array(
'{title}' => get_the_title($post),
'{url}' => get_permalink($post)
);
return str_replace(
array_keys($replacements),
array_values($replacements),
$template
);
}
// 检查是否排除
private function is_excluded($post_id) {
// 检查元数据排除标记
if (get_post_meta($post_id, '_ass_exclude', true)) {
return true;
}
// 检查分类排除
$excluded_categories = isset($this->options['excluded_categories']) ?
$this->options['excluded_categories'] : array();
if (!empty($excluded_categories)) {
$post_categories = wp_get_post_categories($post_id, array('fields' => 'ids'));
$intersection = array_intersect($post_categories, $excluded_categories);
if (!empty($intersection)) {
return true;
}
}
// 检查标签排除
$excluded_tags = isset($this->options['excluded_tags']) ?
$this->options['excluded_tags'] : array();
if (!empty($excluded_tags)) {
$post_tags = wp_get_post_tags($post_id, array('fields' => 'ids'));
$tag_ids = array();
foreach ($post_tags as $tag) {
$tag_ids[] = $tag->term_id;
}
$intersection = array_intersect($tag_ids, $excluded_tags);
if (!empty($intersection)) {
return true;
}
}
return false;
}
// 发送通知
private function send_notification($post_id, $results) {
$send_notifications = isset($this->options['send_notifications']) ?
$this->options['send_notifications'] : false;
if (!$send_notifications) {
return;
}
$admin_email = get_option('admin_email');
$post = get_post($post_id);
$subject = sprintf(__('文章已同步到社交媒体: %s', 'auto-social-sync'), get_the_title($post));
$message = sprintf(__('文章 "%s" 已同步到以下社交媒体平台:', 'auto-social-sync'), get_the_title($post)) . "nn";
foreach ($results as $platform => $result) {
if (is_wp_error($result)) {
$message .= sprintf(__('%s: 失败 - %s', 'auto-social-sync'),
ucfirst($platform),
$result->get_error_message()
) . "n";
} else {
$message .= sprintf(__('%s: 成功', 'auto-social-sync'), ucfirst($platform)) . "n";
}
}
$message .= "n" . sprintf(__('文章链接: %s', 'auto-social-sync'), get_permalink($post));
wp_mail($admin_email, $subject, $message);
}
// 添加快捷发布按钮
public function add_publish_actions() {
global $post;
if (!$post || $post->post_status !== 'publish') {
return;
}
// 检查是否已发布
$already_published = get_post_meta($post->ID, '_ass_published', true);
?>
<div class="misc-pub-section misc-pub-ass-social">
<span class="dashicons dashicons-share"></span>
<?php _e('社交媒体同步:', 'auto-social-sync'); ?>
<span id="ass-status">
<?php if ($already_published): ?>
<span class="ass-published"><?php _e('已同步', 'auto-social-sync'); ?></span>
<?php else: ?>
<span class="ass-not-published"><?php _e('未同步', 'auto-social-sync'); ?></span>
<?php endif; ?>
</span>
<a href="#" id="ass-manual-sync" class="button button-small"
data-post-id="<?php echo $post->ID; ?>"
data-nonce="<?php echo wp_create_nonce('ass_manual_sync_' . $post->ID); ?>">
<?php _e('手动同步', 'auto-social-sync'); ?>
</a>
<div id="ass-sync-results" style="display:none; margin-top:10px;"></div>
</div>
<script>
jQuery(document).ready(function($) {
$('#ass-manual-sync').on('click', function(e) {
e.preventDefault();
var $button = $(this);
var postId = $button.data('post-id');
var nonce = $button.data('nonce');
$button.prop('disabled', true).text('<?php _e('同步中...', 'auto-social-sync'); ?>');
$('#ass-sync-results').hide().empty();
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'ass_manual_sync',
post_id: postId,
nonce: nonce
},
success: function(response) {
if (response.success) {
$('#ass-status').html('<span class="ass-published"><?php _e('已同步', 'auto-social-sync'); ?></span>');
$('#ass-sync-results').html('<div class="notice notice-success inline"><p>' +
'<?php _e('同步成功!', 'auto-social-sync'); ?>' +
'</p></div>').show();
} else {
$('#ass-sync-results').html('<div class="notice notice-error inline"><p>' +
response.data +
'</p></div>').show();
}
},
error: function() {
$('#ass-sync-results').html('<div class="notice notice-error inline"><p>' +
'<?php _e('请求失败,请重试', 'auto-social-sync'); ?>' +
'</p></div>').show();
},
complete: function() {
$button.prop('disabled', false).text('<?php _e('手动同步', 'auto-social-sync'); ?>');
}
});
});
});
</script>
<style>
.ass-published { color: #46b450; font-weight: bold; }
.ass-not-published { color: #f56e28; font-weight: bold; }
.misc-pub-ass-social { border-top: 1px solid #eee; padding-top: 10px; }
</style>
<?php
}
// 处理手动同步请求
public function handle_manual_sync() {
if (!isset($_POST['post_id']) || !isset($_POST['nonce'])) {
wp_die(__('参数错误', 'auto-social-sync'));
}
$post_id = intval($_POST['post_id']);
$nonce = sanitize_text_field($_POST['nonce']);
if (!wp_verify_nonce($nonce, 'ass_manual_sync_' . $post_id)) {
wp_die(__('安全验证失败', 'auto-social-sync'));
}
if (!current_user_can('edit_post', $post_id)) {
wp_die(__('权限不足', 'auto-social-sync'));
}
$post = get_post($post_id);
if (!$post || $post->post_status !== 'publish') {
wp_die(__('文章不存在或未发布', 'auto-social-sync'));
}
// 准备消息
$message = $this->prepare_social_message($post);
// 发布到社交媒体
$results = $this->social_api->publish_to_all($post_id, $message);
// 标记为已发布
update_post_meta($post_id, '_ass_published', current_time('mysql'));
update_post_meta($post_id, '_ass_publish_results', $results);
// 检查结果
$has_error = false;
foreach ($results as $result) {
if (is_wp_error($result)) {
$has_error = true;
break;
}
}
if ($has_error) {
wp_send_json_error(__('部分平台同步失败', 'auto-social-sync'));
} else {
wp_send_json_success(__('同步成功', 'auto-social-sync'));
}
}
}
第四章:管理界面开发
4.1 创建设置页面
管理界面是插件的重要组成部分,让用户可以配置插件功能。
<?php
// includes/class-admin-settings.php
class ASS_Admin_Settings {
private $social_api;
private $options;
private $page_hook;
public function __construct($social_api) {
$this->social_api = $social_api;
$this->options = get_option('ass_settings', array());
$this->init_hooks();
}
// 初始化钩子
private function init_hooks() {
// 添加管理菜单
add_action('admin_menu', array($this, 'add_admin_menu'));
// 注册设置
add_action('admin_init', array($this, 'register_settings'));
// 添加设置链接到插件页面
add_filter('plugin_action_links_' . ASS_PLUGIN_BASENAME, array($this, 'add_plugin_action_links'));
// 加载管理脚本和样式
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
// 添加文章列表列
add_filter('manage_post_posts_columns', array($this, 'add_social_columns'));
add_action('manage_post_posts_custom_column', array($this, 'render_social_columns'), 10, 2);
// 添加批量操作
add_filter('bulk_actions-edit-post', array($this, 'add_bulk_actions'));
add_filter('handle_bulk_actions-edit-post', array($this, 'handle_bulk_actions'), 10, 3);
// AJAX处理
add_action('wp_ajax_ass_test_connection', array($this, 'ajax_test_connection'));
add_action('wp_ajax_ass_get_logs', array($this, 'ajax_get_logs'));
}
// 添加管理菜单
public function add_admin_menu() {
$this->page_hook = add_menu_page(
