如何在WordPress文章循环中创建带自定义图片的Facebook分享链接
核心原因
Facebook 早已不再支持通过sharer.php的URL参数直接传递分享标题、图片、摘要等自定义内容,目前它只会抓取你传入的目标链接页面内的Open Graph(OG)元标签来获取分享素材,这就是你自定义参数不生效、只显示站点logo的根本原因。
解决步骤
1. 给文章页面添加Open Graph元标签
将以下代码添加到你WordPress站点当前主题的functions.php文件中,即可为单篇文章自动插入符合Facebook要求的OG元标签:
// 插入文章页自定义Open Graph元标签 add_action('wp_head', 'insert_custom_og_tags'); function insert_custom_og_tags() { // 仅在单篇文章页生效 if (is_singular('post')) { global $post; $og_title = get_the_title($post->ID); $og_desc = wp_strip_all_tags(get_the_excerpt($post->ID)); $og_img = get_the_post_thumbnail_url($post->ID, 'full'); $og_url = get_permalink($post->ID); echo '<meta property="og:title" content="'.esc_attr($og_title).'" />'; echo '<meta property="og:type" content="article" />'; echo '<meta property="og:url" content="'.esc_url($og_url).'" />'; echo '<meta property="og:description" content="'.esc_attr($og_desc).'" />'; if ($og_img) { echo '<meta property="og:image" content="'.esc_url($og_img).'" />'; } } }
注:分享用的特色图建议尺寸至少为1200630像素,否则可能无法正常展示。*
2. 简化分享链接格式
你原有的分享链接中多余的p[]参数已经无效,直接替换为仅带目标链接参数的格式即可:
<a title="Share this on Facebook!" style="color:#4267B2;" onclick="return !window.open(this.href, 'Facebook', 'width=640,height=300')" href="https://www.facebook.com/sharer.php?u=<?php echo urlencode($url); ?>">Share on Facebook</a>
特殊场景适配
如果你需要分享的内容和文章页面本身展示的OG内容不同,可以用动态参数方案实现:
- 调整上述OG标签输出逻辑,优先读取URL的GET参数作为OG内容:
// 插入支持动态参数的Open Graph元标签 add_action('wp_head', 'insert_dynamic_og_tags'); function insert_dynamic_og_tags() { if (is_singular('post')) { global $post; // 优先取URL传递的分享参数,没有则用文章默认内容 $og_title = isset($_GET['share_title']) ? sanitize_text_field(urldecode($_GET['share_title'])) : get_the_title($post->ID); $og_desc = isset($_GET['share_summary']) ? sanitize_text_field(urldecode($_GET['share_summary'])) : wp_strip_all_tags(get_the_excerpt($post->ID)); $og_img = isset($_GET['share_img']) ? esc_url_raw(urldecode($_GET['share_img'])) : get_the_post_thumbnail_url($post->ID, 'full'); $og_url = get_permalink($post->ID); echo '<meta property="og:title" content="'.esc_attr($og_title).'" />'; echo '<meta property="og:type" content="article" />'; echo '<meta property="og:url" content="'.esc_url($og_url).'" />'; echo '<meta property="og:description" content="'.esc_attr($og_desc).'" />'; if ($og_img) { echo '<meta property="og:image" content="'.esc_url($og_img).'" />'; } } }
- 调整短代码中的分享链接,拼接自定义参数:
<?php // 拼接带自定义分享参数的URL $share_url = add_query_arg([ 'share_title' => urlencode($name), 'share_summary' => urlencode(get_the_excerpt()), 'share_img' => urlencode($img) ], $url); ?> <a title="Share this on Facebook!" style="color:#4267B2;" onclick="return !window.open(this.href, 'Facebook', 'width=640,height=300')" href="https://www.facebook.com/sharer.php?u=<?php echo urlencode($share_url); ?>">Share on Facebook</a>
缓存问题处理
Facebook会对抓取过的页面内容做缓存,如果修改后还是显示旧的分享内容,可以给分享的目标URL末尾加临时查询参数(比如?v=1),即可触发Facebook重新抓取页面内容。
内容的提问来源于stack exchange,提问作者Alex Douglas
相关产品推荐
相关产品推荐

