Automatically Sync WordPress Posts to Sina Weibo (with Images)
The following code enables automatic synchronization of a WordPress post's title, excerpt, and an image to Sina Weibo upon publication. This solution uses a custom field to control syncing and supports using either the post's featured image or its first embedded image as the Weibo attachment.
Core Synchronization Function
Add the following code to your theme's functions.php file:
/**
* Sync WordPress post to Sina Weibo (with image & custom field control)
* Note: Requires a Sina Weibo app key from the open platform.
*/
function post_to_sina_weibo($post_ID) {
// Prevent duplicate posts using custom field 'weibo_sync'
if (get_post_meta($post_ID, 'weibo_sync', true) == 1) return;
$post = get_post($post_ID);
// Sync only on first publish
if ($post->post_status == 'publish' && $_POST['original_post_status'] != 'publish') {
$appkey = 'YOUR_APP_KEY'; // Replace with your app key
$username = 'YOUR_WEIBO_USERNAME'; // Use OAuth2 in production
$userpassword = 'YOUR_WEIBO_PASSWORD'; // Use OAuth2 in production
$request = new WP_Http;
$keywords = '';
// Use post tags as hashtags
$tags = wp_get_post_tags($post_ID);
foreach ($tags as $tag) {
$keywords .= '#' . $tag->name . '#';
}
// Build Weibo content
$string1 = '【文章发布】' . strip_tags($post->post_title) . ':';
$string2 = $keywords . ' 查看全文:' . get_permalink($post_ID);
$wb_num = (138 - weibo_length($string1 . $string2)) * 2;
$status = $string1 . mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, $wb_num, '...') . $string2;
// Get image: featured image first, then first content image
$url = '';
if (has_post_thumbnail()) {
$timthumb_src = wp_get_attachment_image_src(get_post_thumbnail_id($post_ID), 'full');
$url = $timthumb_src[0];
} elseif (function_exists('catch_first_image')) {
$url = catch_first_image();
}
// Choose API endpoint based on image presence
if (!empty($url)) {
$api_url = 'https://api.weibo.com/2/statuses/upload_url_text.json';
$body = array('status' => $status, 'source' => $appkey, 'url' => $url);
} else {
$api_url = 'https://api.weibo.com/2/statuses/update.json';
$body = array('status' => $status, 'source' => $appkey);
}
// Note: Basic Auth is deprecated; use OAuth2
$headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword"));
$result = $request->post($api_url, array('body' => $body, 'headers' => $headers));
// Mark as synced
add_post_meta($post_ID, 'weibo_sync', 1, true);
}
}
add_action('publish_post', 'post_to_sina_weibo', 0);
Helper: Calculate Weibo Character Length
Function to calculate display length for mixed Chinese/English text:
/**
* Calculate Weibo display length (Chinese = 1, English = 0.5)
*/
function weibo_length($str) {
$arr = arr_split_zh($str);
$len = 0;
foreach ($arr as $v) {
$temp = ord($v);
if ($temp > 0 && $temp < 127) {
$len += 0.5;
} else {
$len++;
}
}
return ceil($len);
}
/**
* Split mixed Chinese/English string (GB2312 encoding)
*/
function arr_split_zh($tempaddtext) {
$tempaddtext = iconv("UTF-8", "GBK//IGNORE", $tempaddtext);
$cind = 0;
$arr_cont = array();
for ($i = 0; $i < strlen($tempaddtext); $i++) {
if (strlen(substr($tempaddtext, $cind, 1)) > 0) {
if (ord(substr($tempaddtext, $cind, 1)) < 0xA1) {
array_push($arr_cont, substr($tempaddtext, $cind, 1));
$cind++;
} else {
array_push($arr_cont, substr($tempaddtext, $cind, 2));
$cind += 2;
}
}
}
foreach ($arr_cont as &$row) {
$row = iconv("gb2312", "UTF-8", $row);
}
return $arr_cont;
}
Optional: Get First Post Image
If your theme lacks this function, add this code:
/**
* Extract the first image URL from post content
*/
if (!function_exists('catch_first_image')) {
function catch_first_image() {
global $post;
$first_img = '';
$output = preg_match_all('//i', $post->post_content, $matches);
if (isset($matches[1][0])) {
$first_img = $matches[1][0];
}
return $first_img;
}
}
Usage and Important Notes
- Prerequisite: Apply for a Sina Weibo app at open.weibo.com to get an
App Key. Image sync may require advanced write permissions. - Authorization Update: The provided code uses deprecated Basic Auth. For security, implement OAuth 2.0 and use an
access_token. - Sync Trigger: Sync occurs on first publish if the custom field
weibo_syncis not set to 1. The field is set to 1 after success to prevent duplicates. - Manual Control: Add a custom field
weibo_syncwith value 1 to any post to block automatic sync. - Error Handling: Remove
ini_set('display_errors', true);in production and implement proper logging.
This solution provides a basic framework. Adapt it according to the latest Sina Weibo API requirements, especially regarding authorization.