要让WordPress文章在微信和QQ分享时正确显示图片,你需要添加Open Graph协议代码。以下是纯代码解决方案:
function wechat_share_meta() {
if (is_single()) {
// 基础OG标签
echo '<meta property="og:title" content="'.esc_attr(get_the_title()).'"/>';
echo '<meta property="og:url" content="'.esc_attr(get_permalink()).'"/>';
echo '<meta property="og:description" content="'.esc_attr(wp_strip_all_tags(get_the_excerpt())).'"/>';
// 微信专用图片标签(尺寸建议300x300以上)
if (has_post_thumbnail()) {
$wechat_img = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
echo '<meta property="og:image" content="'.esc_attr($wechat_img[0]).'"/>';
echo '<meta property="twitter:image" content="'.esc_attr($wechat_img[0]).'"/>';
} else {
// 默认LOGO作为备用
echo '<meta property="og:image" content="'.get_template_directory_uri().'/images/share-default.jpg"/>';
}
// 微信专用类型声明
echo '<meta property="og:type" content="article"/>';
echo '<meta name="twitter:card" content="summary_large_image"/>';
}
}
add_action('wp_head', 'wechat_share_meta');
这段代码需要添加到你主题的functions.php文件中。它会自动为每篇文章添加微信和QQ分享所需的Open Graph元数据,包括标题、描述和特色图片。确保你的文章设置了特色图片,这样分享时才能正确显示。
要让WordPress文章在微信和朋友圈分享时正确显示图片,需要额外配置微信专用的JS-SDK和Open Graph协议。以下是完整解决方案:
- 微信JS-SDK配置
微信分享需要特殊授权,必须通过微信公众号后台配置安全域名并引入微信官方JS文件。核心步骤包括:
- 登录微信公众号平台,在”设置→公众号设置→功能设置”中添加JS安全域名
- 下载微信提供的校验文件并上传至网站根目录
- 获取AppID和AppSecret用于生成签名
- 增强版Open Graph代码
微信对Open Graph协议有特殊要求,需在主题的functions.php中添加以下代码:
function wechat_share_meta() {
if (is_single()) {
// 基础OG标签
echo '<meta property="og:title" content="'.esc_attr(get_the_title()).'"/>';
echo '<meta property="og:url" content="'.esc_attr(get_permalink()).'"/>';
echo '<meta property="og:description" content="'.esc_attr(wp_strip_all_tags(get_the_excerpt())).'"/>';
// 微信专用图片标签(尺寸建议300x300以上)
if (has_post_thumbnail()) {
$wechat_img = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
echo '<meta property="og:image" content="'.esc_attr($wechat_img[0]).'"/>';
echo '<meta property="twitter:image" content="'.esc_attr($wechat_img[0]).'"/>';
} else {
// 默认LOGO作为备用
echo '<meta property="og:image" content="'.get_template_directory_uri().'/images/share-default.jpg"/>';
}
// 微信专用类型声明
echo '<meta property="og:type" content="article"/>';
echo '<meta name="twitter:card" content="summary_large_image"/>';
}
}
add_action('wp_head', 'wechat_share_meta');
这段代码会为每篇文章添加微信和Twitter专用的分享元数据,优先使用文章特色图片。
- 常见问题排查
- 图片尺寸需大于300×300像素,微信会拒绝显示过小的图片
- 确保服务器IP在微信公众号平台的IP白名单中
- 微信会缓存分享信息,首次修改后可能需要24小时生效
- 检查网页是否被微信屏蔽(含敏感词或违规内容)
- 插件替代方案
如果代码实现困难,推荐使用专业插件如:
- Bosima WeChat Page Sharing(中文支持好)
- WP Weixin(支持自定义分享文案)
- Yoast SEO(含Open Graph功能)
注意:微信分享功能需要网站启用HTTPS,且所有图片URL也必须使用HTTPS协议。测试时建议使用微信开发者工具的”网页调试”功能验证OG标签是否生效
提示:仅供参考