如何将WordPress用户自定义头像设置为用户页分享时的特色缩略图
实现方案
你可以通过在用户存档页头部输出自定义开放图谱(OG)标签的方式,让社交平台抓取你上传的自定义头像作为分享缩略图,具体实现代码如下:
add_action( 'wp_head', 'custom_author_og_image', 15 ); function custom_author_og_image() { // 只在用户存档页生效 if ( ! is_author() ) return; // 获取当前页面对应用户ID $author_id = get_queried_object_id(); // 读取你存储的自定义头像URL $custom_avatar = get_the_author_meta( 'sidebarimage', $author_id ); // 头像存在则输出OG标签 if ( ! empty( $custom_avatar ) ) { // 输出通用/ Facebook OG头像标签 echo '<meta property="og:image" content="' . esc_url( $custom_avatar ) . '" />'; echo '<meta property="og:image:width" content="600" />'; // 可替换为你头像的实际宽度 echo '<meta property="og:image:height" content="600" />'; // 可替换为你头像的实际高度 // 输出Twitter卡片头像标签 echo '<meta name="twitter:image" content="' . esc_url( $custom_avatar ) . '" />'; } }
注意事项
- 如果你在使用Yoast SEO、Rank Math等第三方SEO插件,需要到插件设置中关闭作者存档页的默认特色图像输出,或者将上述代码钩子的优先级数值调大(比如把15改为25),让自定义标签后输出覆盖原有标签。
- 代码默认优先读取用户上传的自定义头像,如果需要设置兜底默认头像,可以在判断
$custom_avatar为空时,输出你指定的默认头像URL即可。
内容的提问来源于stack exchange,提问作者Milos Markovic
相关产品推荐
相关产品推荐

