博客 / WordPress/ WordPress 文章自动同步到新浪微博(带图片)实现方案

WordPress 文章自动同步到新浪微博(带图片)实现方案

WordPress 文章自动同步到新浪微博(带图片)实现方案

WordPress 文章自动同步到新浪微博(带图片)

以下代码实现了在 WordPress 发布文章时,自动将文章标题、摘要及图片同步到新浪微博的功能。该方案通过自定义栏目控制同步,并支持使用文章特色图片或首张图片作为微博配图。

核心同步函数

将以下代码添加到主题的 functions.php 文件中:

/**
 * WordPress发布文章同步到新浪微博(带图片&自定义栏目版)
 * 注意:使用前需申请新浪微博开放平台应用并获取 App Key。
 */
function post_to_sina_weibo($post_ID) {
    // 调试模式,正式使用可注释掉
    ini_set('display_errors', true);

    // 通过自定义栏目 weibo_sync 判断是否已同步,避免重复发布
    if (get_post_meta($post_ID, 'weibo_sync', true) == 1) return;

    $post = get_post($post_ID);
    $post_content = $post->post_content;
    $post_title = $post->post_title;

    // 仅在文章首次发布时触发同步
    if ($post->post_status == 'publish' && $_POST['original_post_status'] != 'publish') {
        $appkey = 'YOUR_APP_KEY'; // 替换为你的微博应用 App Key
        $username = 'YOUR_WEIBO_USERNAME'; // 微博账号(现建议使用 OAuth2,此处为示例)
        $userpassword = 'YOUR_WEIBO_PASSWORD'; // 微博密码(现建议使用 OAuth2,此处为示例)
        $request = new WP_Http;
        $keywords = '';

        // 获取文章标签作为微博话题
        $tags = wp_get_post_tags($post_ID);
        foreach ($tags as $tag) {
            $keywords .= '#' . $tag->name . '#';
        }

        // 构建微博内容:标题 + 摘要 + 链接
        $string1 = '【文章发布】' . strip_tags($post_title) . ':';
        $string2 = $keywords . ' 查看全文:' . get_permalink($post_ID);

        // 微博字数控制(微博标准为 140 字,此处预留空间)
        $wb_num = (138 - weibo_length($string1 . $string2)) * 2;
        $status = $string1 . mb_strimwidth(strip_tags(apply_filters('the_content', $post_content)), 0, $wb_num, '...') . $string2;

        // 获取配图:优先使用特色图片,其次使用文章首张图片
        $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();
        }

        // 根据是否有图片选择不同的 API 接口
        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);
        }

        // 注意:此处使用 Basic Auth 已过时,建议改用 OAuth2 授权
        $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword"));
        $result = $request->post($api_url, array('body' => $body, 'headers' => $headers));

        // 同步成功后添加标记,避免重复同步
        add_post_meta($post_ID, 'weibo_sync', 1, true);
    }
}
add_action('publish_post', 'post_to_sina_weibo', 0);

辅助函数:计算微博字符长度

微博中英文混合字符长度计算函数:

/**
 * 计算字符串的微博显示长度(中文算1,英文算0.5)
 */
function weibo_length($str) {
    $arr = arr_split_zh($str); // 将字符串分割到数组中
    $len = 0;
    foreach ($arr as $v) {
        $temp = ord($v); // 转换为 ASCII 码
        if ($temp > 0 && $temp < 127) {
            $len += 0.5;
        } else {
            $len++;
        }
    }
    return ceil($len); // 向上取整
}

/**
 * 拆分中英混合字符串(支持 GB2312 编码)
 * 参考:http://u-czh.iteye.com/blog/1565858
 */
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) { // 如果为英文则取1个字节
                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;
}

获取文章首张图片函数(可选)

如果主题没有提供抓取文章首张图片的功能,可添加以下代码:

/**
 * 抓取文章内容中的第一张图片 URL
 */
if (!function_exists('catch_first_image')) {
    function catch_first_image() {
        global $post;
        $first_img = '';
        ob_start();
        ob_end_clean();
        // 使用 $post->post_content 而非 $get_post_centent(原代码变量名有误)
        $output = preg_match_all('//i', $post->post_content, $matches);
        if (isset($matches[1][0])) {
            $first_img = $matches[1][0];
        }
        return $first_img;
    }
}

使用说明与注意事项

  1. 前提条件:你需要在新浪微博开放平台(open.weibo.com)申请一个应用,获取 App Key。使用图片同步功能可能需要申请“高级写入权限”。
  2. 授权方式更新:原代码使用 Basic Auth(用户名密码)已过时且不安全。强烈建议改用 OAuth 2.0 授权。你需要修改代码,使用获取到的 access_token 进行 API 调用。
  3. 触发同步:文章发布时,若自定义栏目 weibo_sync 不存在或不为 1,则会触发同步。同步成功后会添加该栏目值为 1,防止更新文章时重复发布。
  4. 自定义控制:你可以在文章编辑页面添加自定义栏目 weibo_sync,并设置值为 1 来手动阻止同步。
  5. 错误处理:建议在生产环境中移除 ini_set('display_errors', true);,并添加更完善的错误日志记录。

此方案提供了一个基础的自动同步思路,实际使用时请根据微博 API 的最新要求(尤其是授权方式)进行调整。

发表评论

您的邮箱不会公开。必填项已用 * 标注。