目前还没测试,最近挺忙的,等有空来试试。
将以下代码保存为weibo-auto-sync.php
文件,并放置在/wp-content/plugins/weibo-auto-sync/
目录下:
<?php
/**
* Plugin Name: Weibo Auto Sync
* Description: 自动将WordPress文章同步到新浪微博
* Version: 1.0.0
* Author: 万事屋的阿银
* License: GPL v2 or later
*/
// 避免直接访问
if (!defined('ABSPATH')) {
exit;
}
// 创建管理菜单
add_action('admin_menu', 'weibo_sync_admin_menu');
function weibo_sync_admin_menu() {
add_options_page(
'微博同步设置',
'微博同步',
'manage_options',
'weibo-sync-settings',
'weibo_sync_settings_page'
);
}
// 设置页面
function weibo_sync_settings_page() {
?>
<div class="wrap">
<h1>微博同步设置</h1>
<form method="post" action="options.php">
<?php
settings_fields('weibo_sync_settings_group');
do_settings_sections('weibo-sync-settings');
submit_button();
?>
</form>
</div>
<?php
}
// 注册设置
add_action('admin_init', 'weibo_sync_register_settings');
function weibo_sync_register_settings() {
register_setting('weibo_sync_settings_group', 'weibo_sync_access_token');
register_setting('weibo_sync_settings_group', 'weibo_sync_include_categories');
register_setting('weibo_sync_settings_group', 'weibo_sync_template');
add_settings_section(
'weibo_sync_main_section',
'API设置',
null,
'weibo-sync-settings'
);
add_settings_field(
'weibo_sync_access_token',
'微博Access Token',
'weibo_sync_token_callback',
'weibo-sync-settings',
'weibo_sync_main_section'
);
add_settings_field(
'weibo_sync_include_categories',
'同步的分类',
'weibo_sync_categories_callback',
'weibo-sync-settings',
'weibo_sync_main_section'
);
add_settings_field(
'weibo_sync_template',
'微博内容模板',
'weibo_sync_template_callback',
'weibo-sync-settings',
'weibo_sync_main_section'
);
}
function weibo_sync_token_callback() {
$token = get_option('weibo_sync_access_token');
echo '<input type="text" name="weibo_sync_access_token" value="' . esc_attr($token) . '" style="width: 300px;" />';
echo '<p class="description">需要在<a href="https://www.rei3.com/?golink=aHR0cHM6Ly9vcGVuLndlaWJvLmNvbS8=" target="_blank">微博开放平台</a>申请应用并获取Access Token</p>';
}
function weibo_sync_categories_callback() {
$categories = get_categories();
$selected_categories = get_option('weibo_sync_include_categories', array());
foreach ($categories as $category) {
$checked = in_array($category->term_id, $selected_categories) ? 'checked' : '';
echo '<label><input type="checkbox" name="weibo_sync_include_categories[]" value="' . $category->term_id . '" ' . $checked . '> ' . $category->name . '</label><br>';
}
echo '<p class="description">只同步所选分类的文章(不选则同步所有分类)</p>';
}
function weibo_sync_template_callback() {
$template = get_option('weibo_sync_template', '%title%:%excerpt% %link%');
echo '<textarea name="weibo_sync_template" style="width: 300px; height: 100px;">' . esc_textarea($template) . '</textarea>';
echo '<p class="description">可用变量: %title%, %excerpt%, %content%, %link%, %category%</p>';
}
// 文章发布时同步到微博
add_action('publish_post', 'weibo_sync_on_publish');
function weibo_sync_on_publish($post_id) {
// 检查是否已同步过,避免重复发布
if (get_post_meta($post_id, '_weibo_synced', true)) {
return;
}
// 检查文章分类是否在选定同步范围内
$selected_categories = get_option('weibo_sync_include_categories', array());
if (!empty($selected_categories)) {
$post_categories = wp_get_post_categories($post_id);
$intersect = array_intersect($selected_categories, $post_categories);
if (empty($intersect)) {
return;
}
}
$post = get_post($post_id);
$title = get_the_title($post_id);
$excerpt = wp_trim_words($post->post_content, 120, '...');
$content = strip_tags($post->post_content);
$link = get_permalink($post_id);
$categories = get_the_category($post_id);
$category_names = array();
foreach ($categories as $category) {
$category_names[] = $category->name;
}
$template = get_option('weibo_sync_template', '%title%:%excerpt% %link%');
$status = str_replace(
array('%title%', '%excerpt%', '%content%', '%link%', '%category%'),
array($title, $excerpt, $content, $link, implode(',', $category_names)),
$template
);
// 限制微博长度(2000字符以内)
if (mb_strlen($status) > 2000) {
$status = mb_substr($status, 0, 1997) . '...';
}
// 获取文章中的第一张图片
$image_url = '';
if (has_post_thumbnail($post_id)) {
$image_url = get_the_post_thumbnail_url($post_id, 'full');
} else {
preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (!empty($matches[1])) {
$image_url = $matches[1];
}
}
// 发送到微博
$access_token = get_option('weibo_sync_access_token');
$result = weibo_sync_send_weibo($access_token, $status, $image_url);
if ($result && !is_wp_error($result)) {
// 标记为已同步
update_post_meta($post_id, '_weibo_synced', true);
add_post_meta($post_id, '_weibo_sync_time', current_time('mysql'), true);
add_post_meta($post_id, '_weibo_sync_result', $result, true);
}
}
// 发送微博函数
function weibo_sync_send_weibo($access_token, $status, $image_url = '') {
if (empty($access_token)) {
return new WP_Error('no_token', '未设置微博Access Token');
}
$api_url = 'https://api.weibo.com/2/statuses';
$api_url .= $image_url ? '/upload.json' : '/update.json';
$data = array(
'access_token' => $access_token,
'status' => $status
);
if ($image_url) {
// 下载远程图片
$upload_dir = wp_upload_dir();
$image_data = weibo_sync_download_image($image_url);
if (is_wp_error($image_data)) {
// 图片下载失败,改为发送纯文本微博
$api_url = 'https://api.weibo.com/2/statuses/update.json';
} else {
$data['pic'] = $image_data;
}
}
$args = array(
'body' => $data,
'timeout' => 30
);
$response = wp_remote_post($api_url, $args);
if (is_wp_error($response)) {
return $response;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['error'])) {
return new WP_Error('weibo_api_error', $body['error']);
}
return $body;
}
// 下载图片函数
function weibo_sync_download_image($image_url) {
$response = wp_remote_get($image_url, array('timeout' => 30));
if (is_wp_error($response)) {
return $response;
}
$image_data = wp_remote_retrieve_body($response);
if (empty($image_data)) {
return new WP_Error('image_download_failed', '图片下载失败');
}
return $image_data;
}
// 在文章编辑页面显示同步状态
add_action('add_meta_boxes', 'weibo_sync_add_meta_box');
function weibo_sync_add_meta_box() {
add_meta_box(
'weibo_sync_meta_box',
'微博同步状态',
'weibo_sync_meta_box_callback',
'post',
'side',
'default'
);
}
function weibo_sync_meta_box_callback($post) {
$synced = get_post_meta($post->ID, '_weibo_synced', true);
$sync_time = get_post_meta($post->ID, '_weibo_sync_time', true);
$sync_result = get_post_meta($post->ID, '_weibo_sync_result', true);
if ($synced) {
echo '<p>状态: <strong>已同步到微博</strong></p>';
echo '<p>同步时间: ' . $sync_time . '</p>';
if ($sync_result && isset($sync_result['id'])) {
echo '<p>微博ID: ' . $sync_result['id'] . '</p>';
}
} else {
echo '<p>状态: <strong>未同步</strong></p>';
echo '<p>文章发布后将自动同步到微博</p>';
}
}
-
激活插件:在WordPress后台的”插件”页面中找到”Weibo Auto Sync“并激活。
-
申请微博开放平台权限:
-
访问微博开放平台
-
注册开发者账号并创建新应用
-
选择”网站接入”应用类型
-
获取App Key和App Secret
-
-
获取Access Token:
-
使用微博API测试工具(http://open.weibo.com/tools/console)获取Access Token
-
或者通过OAuth认证流程获取用户授权
-
-
配置插件:
-
在WordPress后台找到”设置 > 微博同步“
-
输入你获取的Access Token
-
选择要同步的文章分类(可选)
-
自定义微博内容模板(可选)
-
微博内容模板变量
可以使用以下变量自定义微博内容格式:
变量 | 说明 |
---|---|
%title% |
文章标题 |
%excerpt% |
文章摘要(120字以内) |
%content% |
文章内容 |
%link% |
文章链接 |
%category% |
文章分类 |
默认模板:%title%:%excerpt% %link%
🚨 重要注意事项
-
API限制:微博API有调用频率限制,建议不要频繁发布文章。
-
内容长度:微博内容限制为2000字符以内,插件会自动截断过长内容。
-
图片支持:插件会自动获取文章特色图片或正文第一张图片同步到微博。
-
审核要求:确保内容符合微博社区规范,避免发布违规内容。
-
分类过滤:可以选择只同步特定分类的文章,避免所有文章都同步到微博。
-
安全域名:在微博开放平台设置中需配置安全域名,确保与你的网站域名一致。
🔍 故障排除
如果同步功能无法正常工作:
-
检查Access Token是否正确且未过期
-
查看WordPress错误日志(通常位于
/wp-content/debug.log
) -
确保你的服务器支持HT请求和远程图片下载
-
确认微博应用已通过审核且具有足够权限
这个插件提供了基本但完整的微博同步功能,你可以根据需要进一步扩展功能,如添加多账号支持、定时同步、自定义字段映射等。
希望这个解决方案对你有帮助,如果有任何问题或需要进一步的功能扩展,请随时告知。
没有回复内容