如何为wp_usermeta存储的用户头像应用自定义缩略图尺寸?
解决方案:为自定义用户头像应用WordPress缩略图尺寸
嘿,我来帮你搞定这个问题!你已经在wp_usermeta里存了自定义头像,也定义了blog-author-thumbnail尺寸,现在只需要把获取到的头像数据和WordPress的缩略图系统对接起来就行。这里分两种常见情况处理:
情况1:user_profile_image存储的是图片附件ID
如果你的字段存的是上传图片时生成的附件ID(这是推荐的存储方式,比存URL更灵活),直接用wp_get_attachment_image_src()就能拿到指定尺寸的缩略图:
// 获取当前作者的头像附件ID $profile_image_id = get_the_author_meta( 'user_profile_image', $current_author->ID ); // 检查是否存在有效ID,再获取缩略图 if ( $profile_image_id ) { // 传入自定义尺寸名称,获取缩略图数据 $thumbnail_data = wp_get_attachment_image_src( $profile_image_id, 'blog-author-thumbnail' ); if ( $thumbnail_data ) { // 输出安全的img标签 echo '<img src="' . esc_url( $thumbnail_data[0] ) . '" alt="' . esc_attr( get_the_author_meta('display_name', $current_author->ID) ) . '" width="' . $thumbnail_data[1] . '" height="' . $thumbnail_data[2] . '" >'; } }
情况2:user_profile_image存储的是图片URL
如果你的字段存的是直接的图片URL,先把URL转换成附件ID,再用同样的方法获取缩略图:
// 获取当前作者的头像URL $profile_image_url = get_the_author_meta( 'user_profile_image', $current_author->ID ); // 将URL转换为对应的附件ID $profile_image_id = attachment_url_to_postid( $profile_image_url ); // 后续逻辑和情况1一致 if ( $profile_image_id ) { $thumbnail_data = wp_get_attachment_image_src( $profile_image_id, 'blog-author-thumbnail' ); if ( $thumbnail_data ) { echo '<img src="' . esc_url( $thumbnail_data[0] ) . '" alt="' . esc_attr( get_the_author_meta('display_name', $current_author->ID) ) . '" width="' . $thumbnail_data[1] . '" height="' . $thumbnail_data[2] . '" >'; } }
更简洁的写法:直接输出完整img标签
如果你不想手动拼接img标签,可以用wp_get_attachment_image()函数,它会直接生成安全的完整标签:
$profile_image_id = get_the_author_meta( 'user_profile_image', $current_author->ID ); if ( $profile_image_id ) { echo wp_get_attachment_image( $profile_image_id, 'blog-author-thumbnail', false, // 是否作为图标(一般设为false) array( 'alt' => esc_attr( get_the_author_meta('display_name', $current_author->ID) ) ) // 自定义属性 ); }
重要注意事项
- 如果你是在添加
add_image_size之后才上传的头像,缩略图会自动生成;但如果是之前上传的旧头像,需要用Regenerate Thumbnails插件重新生成所有缩略图,否则blog-author-thumbnail尺寸的图片不会存在。 - 所有输出的URL和属性都要用
esc_url()、esc_attr()转义,避免XSS安全漏洞。
内容的提问来源于stack exchange,提问作者Subrata Sarkar
相关产品推荐
相关产品推荐

