最簡單方式:構造 sharer.php 鏈接,用戶點擊跳轉 Facebook 分享頁。
<a href="https://www.facebook.com/sharer.php?u=https://example.com/page&t=分享標題"
target="_blank"
onclick="window.open(this.href, 'fbShare', 'width=800,height=400'); return false;">
分享到 Facebook
</a>
u:要分享的目標 URL(需 encodeURIComponent)。t:分享標題(可選,Facebook 會優先抓取頁面 OG 標簽)。在目標頁面 <head> 中添加以下 Meta 標簽,Facebook 爬蟲抓取時將優先使用這些信息生成豐富分享卡片:
<meta property="og:title" content="自定義分享標題" />
<meta property="og:description" content="自定義分享描述內容" />
<meta property="og:image" content="https://example.com/share-image.jpg" />
<meta property="og:url" content="https://example.com/page" />
<meta property="og:type" content="website" />
若需更豐富的交互(如指定標題、描述、圖片、鏈接、回調),可接入 Facebook JS SDK:
<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/zh_TW/sdk.js#xfbml=1&version=v18.0"></script>
<button onclick="shareToFb()">分享</button>
<script>
function shareToFb() {
FB.ui({
method: 'share_open_graph',
action_type: 'og.shares',
action_properties: JSON.stringify({
object: {
'og:url': 'https://example.com/page',
'og:title': '自定義標題',
'og:description': '自定義描述',
'og:image': 'https://example.com/img.jpg'
}
})
}, function(response) {
if (response && !response.error_message) {
alert('分享成功');
}
});
}
</script>
<?php
function buildFbShareUrl($url, $title = '') {
$base = 'https://www.facebook.com/sharer.php';
$params = [
'u' => $url,
];
if ($title) $params['quote'] = $title; // quote 參數可預填用戶發文文本
return $base . '?' . http_build_query($params);
}
// 使用
$shareUrl = buildFbShareUrl('https://example.com/article/123', '精彩文章標題');
echo '<a href="' . $shareUrl . '" target="_blank">分享</a>';
og:image 是否為 HTTPS、尺寸是否達標、是否允許 Facebook 爬蟲訪問(User-Agent 含 facebookexternalhit)。靜態頁面用 sharer.php + OG 標簽最輕量;單頁應用或需回調用 JS SDK。核心在於正確部署 OG 標簽並善用調試工具。