WordPress 模板里添加社交分享按钮(纯代码实现)

纯代码实现WordPress 模板里添加社交分享按钮

支持平台:

国外平台📘Facebook 🐦X(Twitter) 🔗LinkedIn 📌Pinterest 💬WhatsApp ✈️Telegram 🤖Reddit ✉️邮件

国内平台不能少 QQ、微信、微博 以及 QQ空间,这些都是国内用户高频使用的分享渠道。

1. 在 functions.php 中添加分享按钮函数

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

// 社交分享按钮函数
function custom_social_share_buttons() {
    // 获取当前文章/页面的标题和链接
    $post_title = get_the_title();
    $post_url = urlencode(get_permalink());
    $post_title_encoded = urlencode($post_title);
    
    // 获取特色图片(用于 Pinterest 和微博)
    $thumbnail_url = '';
    if (has_post_thumbnail()) {
        $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'large');
        $thumbnail_url = urlencode($thumbnail[0]);
    }
    
    // 各平台分享链接
    $platforms = array(
        // ========== 国内平台 ==========
        'wechat' => array(
            'name' => '微信',
            'url' => 'javascript:void(0);', // 微信需要特殊处理
            'icon' => '💚',
            'special' => 'wechat'  // 标记为特殊处理
        ),
        'weibo' => array(
            'name' => '微博',
            'url' => 'https://service.weibo.com/share/share.php?title=' . $post_title_encoded . '&url=' . $post_url . '&pic=' . $thumbnail_url,
            'icon' => '🔴'
        ),
        'qq' => array(
            'name' => 'QQ好友',
            'url' => 'https://connect.qq.com/widget/shareqq/index.html?url=' . $post_url . '&title=' . $post_title_encoded . '&pics=' . $thumbnail_url,
            'icon' => '🐧'
        ),
        'qzone' => array(
            'name' => 'QQ空间',
            'url' => 'https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' . $post_url . '&title=' . $post_title_encoded . '&pics=' . $thumbnail_url,
            'icon' => '💛'
        ),
        'douban' => array(
            'name' => '豆瓣',
            'url' => 'https://www.douban.com/share/service?href=' . $post_url . '&name=' . $post_title_encoded,
            'icon' => '📗'
        ),
        // ========== 国际平台 ==========
        'facebook' => array(
            'name' => 'Facebook',
            'url' => 'https://www.facebook.com/sharer/sharer.php?u=' . $post_url,
            'icon' => '📘'
        ),
        'twitter' => array(
            'name' => 'X(Twitter)',
            'url' => 'https://twitter.com/intent/tweet?text=' . $post_title_encoded . '&url=' . $post_url,
            'icon' => '🐦'
        ),
        'linkedin' => array(
            'name' => 'LinkedIn',
            'url' => 'https://www.linkedin.com/sharing/share-offsite/?url=' . $post_url,
            'icon' => '🔗'
        ),
        'pinterest' => array(
            'name' => 'Pinterest',
            'url' => 'https://pinterest.com/pin/create/button/?url=' . $post_url . '&media=' . $thumbnail_url . '&description=' . $post_title_encoded,
            'icon' => '📌'
        ),
        'whatsapp' => array(
            'name' => 'WhatsApp',
            'url' => 'https://api.whatsapp.com/send?text=' . $post_title_encoded . '%20' . $post_url,
            'icon' => '💬'
        ),
        'telegram' => array(
            'name' => 'Telegram',
            'url' => 'https://t.me/share/url?url=' . $post_url . '&text=' . $post_title_encoded,
            'icon' => '✈️'
        ),
        'reddit' => array(
            'name' => 'Reddit',
            'url' => 'https://reddit.com/submit?url=' . $post_url . '&title=' . $post_title_encoded,
            'icon' => '🤖'
        ),
        'email' => array(
            'name' => '邮件',
            'url' => 'mailto:?subject=' . $post_title_encoded . '&body=Check%20this%20out:%20' . $post_url,
            'icon' => '✉️'
        )
    );
    
    $output = '<div class="social-share-buttons">';
    $output .= '<span class="share-label">📤 分享到:</span>';
    
    foreach ($platforms as $key => $platform) {
        // 微信特殊处理
        if (isset($platform['special']) && $platform['special'] == 'wechat') {
            $output .= '<button type="button" ';
            $output .= 'class="share-btn share-wechat" ';
            $output .= 'onclick="showWechatQR()" ';
            $output .= 'aria-label="分享到微信">';
            $output .= '<span class="share-icon">' . $platform['icon'] . '</span>';
            $output .= '<span class="share-name">' . $platform['name'] . '</span>';
            $output .= '</button>';
        } else {
            $output .= '<a href="' . $platform['url'] . '" ';
            $output .= 'target="_blank" ';
            $output .= 'rel="noopener noreferrer" ';
            $output .= 'class="share-btn share-' . $key . '" ';
            $output .= 'aria-label="分享到 ' . $platform['name'] . '">';
            $output .= '<span class="share-icon">' . $platform['icon'] . '</span>';
            $output .= '<span class="share-name">' . $platform['name'] . '</span>';
            $output .= '</a>';
        }
    }
    
    $output .= '</div>';
    
    // 微信弹窗(放在输出末尾)
    $output .= '
    <!-- 微信分享弹窗 -->
    <div id="wechat-qr-modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.6);z-index:9999;justify-content:center;align-items:center;">
        <div style="background:#fff;padding:30px 40px;border-radius:12px;text-align:center;max-width:340px;width:90%;">
            <h3 style="margin:0 0 10px 0;font-size:18px;">📱 微信分享</h3>
            <p style="font-size:14px;color:#666;margin-bottom:15px;">请使用微信扫一扫分享</p>
            <div id="wechat-qr-container" style="background:#f5f5f5;padding:15px;border-radius:8px;display:inline-block;">
                <div id="wechat-qr-placeholder" style="width:200px;height:200px;display:flex;justify-content:center;align-items:center;color:#999;font-size:14px;border:2px dashed #ddd;border-radius:8px;">
                    ⏳ 加载中...
                </div>
            </div>
            <button onclick="closeWechatQR()" style="margin-top:15px;padding:8px 30px;border:none;background:#07C160;color:#fff;border-radius:6px;font-size:14px;cursor:pointer;">关闭</button>
            <p style="font-size:12px;color:#999;margin-top:10px;">或复制链接分享:<span id="wechat-copy-url" style="color:#07C160;cursor:pointer;">点击复制</span></p>
        </div>
    </div>
    ';
    
    return $output;
}

// 注册简码
add_shortcode('social_share', 'custom_social_share_buttons');

2. 在模板文件中调用

在你想要显示分享按钮的地方(如 single.phppage.php 或 content.php 中),添加:

<?php echo custom_social_share_buttons(); ?>

或者如果你使用的是简码方式,在文章编辑器中输入:

[social_share]

3. CSS 样式

/* 分享按钮容器 */
.social-share-buttons {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    padding: 15px 0;
    margin: 20px 0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
}

.share-label {
    font-weight: 600;
    margin-right: 10px;
    font-size: 14px;
    color: #333;
}

/* 单个按钮基础样式 */
.share-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 4px;
    text-decoration: none;
    font-size: 13px;
    font-weight: 500;
    color: #fff;
    transition: all 0.3s ease;
    border: none;
    cursor: pointer;
}

.share-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    color: #fff;
    text-decoration: none;
}

/* ===== 国内平台品牌色 ===== */
.share-wechat {
    background-color: #07C160;  /* 微信绿 */
}
.share-weibo {
    background-color: #FF8200;  /* 微博橙 */
}
.share-qq {
    background-color: #12B7F5;  /* QQ蓝 */
}
.share-qzone {
    background-color: #FECE00;  /* QQ空间黄 */
    color: #333;
}
.share-qzone:hover {
    color: #333;
}
.share-douban {
    background-color: #2E963D;  /* 豆瓣绿 */
}

/* ===== 国际平台品牌色 ===== */
.share-facebook {
    background-color: #1877F2;
}
.share-twitter {
    background-color: #000000;
}
.share-linkedin {
    background-color: #0A66C2;
}
.share-pinterest {
    background-color: #E60023;
}
.share-whatsapp {
    background-color: #25D366;
}
.share-telegram {
    background-color: #0088CC;
}
.share-reddit {
    background-color: #FF4500;
}
.share-email {
    background-color: #6C757D;
}

/* 图标和文字 */
.share-icon {
    font-size: 16px;
    line-height: 1;
}
.share-name {
    font-size: 12px;
}

/* 响应式:小屏幕只显示图标 */
@media (max-width: 480px) {
    .share-name {
        display: none;
    }
    .share-btn {
        padding: 8px 12px;
    }
}

4. 微信分享的 JavaScript(添加到 footer 或单独 JS 文件)

// 微信分享功能
function showWechatQR() {
    var modal = document.getElementById('wechat-qr-modal');
    modal.style.display = 'flex';
    
    // 生成当前页面的二维码(使用 qrserver.com API)
    var currentUrl = encodeURIComponent(window.location.href);
    var qrContainer = document.getElementById('wechat-qr-placeholder');
    
    // 方案一:使用在线 API 生成二维码(免费,无需 API key)
    qrContainer.innerHTML = '<img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + currentUrl + '" alt="微信分享二维码" style="width:200px;height:200px;">';
    
    // 方案二:如果你自己有服务器,也可以用本地生成的二维码
    // qrContainer.innerHTML = '<img src="/qr-generator.php?url=' + currentUrl + '" alt="微信分享二维码" style="width:200px;height:200px;">';
}

function closeWechatQR() {
    document.getElementById('wechat-qr-modal').style.display = 'none';
}

// 点击弹窗外部关闭
document.addEventListener('DOMContentLoaded', function() {
    var modal = document.getElementById('wechat-qr-modal');
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeWechatQR();
            }
        });
    }
    
    // 复制链接功能
    var copyBtn = document.getElementById('wechat-copy-url');
    if (copyBtn) {
        copyBtn.addEventListener('click', function() {
            var url = window.location.href;
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(url).then(function() {
                    alert('✅ 链接已复制,去微信粘贴给好友吧!');
                }).catch(function() {
                    fallbackCopy(url);
                });
            } else {
                fallbackCopy(url);
            }
        });
    }
});

// 兼容旧浏览器的复制方法
function fallbackCopy(text) {
    var textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    textarea.style.opacity = '0';
    document.body.appendChild(textarea);
    textarea.select();
    try {
        document.execCommand('copy');
        alert('✅ 链接已复制,去微信粘贴给好友吧!');
    } catch (err) {
        alert('❌ 复制失败,请手动复制链接:' + text);
    }
    document.body.removeChild(textarea);
}

如何嵌入微信 JS 代码

在主题的 footer.php 中,wp_footer() 之前添加:

<script>
// 把上面 JavaScript 代码粘贴到这里
</script>

或者更规范的做法:新建一个 share.js 文件,然后在 functions.php 中引入:

function enqueue_share_scripts() {
    if (is_single() || is_page()) {
        wp_enqueue_script('custom-share', get_template_directory_uri() . '/js/share.js', array(), '1.0', true);
    }
}
add_action('wp_enqueue_scripts', 'enqueue_share_scripts');

📌 各平台分享链接说明

平台分享链接格式说明
微信使用二维码 + 复制链接微信禁止直接 URL 跳转分享,只能用二维码或复制链接
微博service.weibo.com/share/share.php支持标题、链接、图片参数
QQ好友connect.qq.com/widget/shareqq/index.html腾讯官方的分享接口
QQ空间sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey一键分享到 QQ 空间
豆瓣douban.com/share/service豆瓣分享接口

可选:按访问地区显示不同平台

如果你想根据用户地域显示不同平台(国内用户看国内平台,国外用户看国际平台),可以这样优化:

function get_user_region() {
    $ip = $_SERVER['REMOTE_ADDR'];
    // 可以使用 IP 归属地 API,这里简化处理
    // 返回 'cn' 或 'global'
    return 'cn'; // 示例
}

// 然后在分享函数中根据 region 过滤平台
$user_region = get_user_region();
// 如果 region == 'cn' 则优先显示国内平台

这样你的分享按钮就覆盖了国内外的全部主流平台了 🎉