请求提供替换WordPress自定义尺寸图片URL的正确代码
WordPress 自定义图片URL替换方案
根据你的需求,以下是两种常见场景下的替换代码,适配WordPress媒体库的图片尺寸调用:
场景1:自定义字段存储图片ID
如果你的自定义字段(比如字段名custom_image)保存的是媒体库图片ID,用这段代码替换原有逻辑:
// 获取自定义字段中的图片ID $image_id = get_post_meta(get_the_ID(), 'custom_image', true); // 替换为你需要的目标尺寸名称 $target_size = 'medium_large'; // 获取对应尺寸的图片URL $image_url = $image_id ? wp_get_attachment_image_url($image_id, $target_size) : ''; // 输出示例(按需调整) if ($image_url) { echo '<img src="' . esc_url($image_url) . '" alt="' . esc_attr(get_the_title()) . '">'; }
场景2:自定义字段存储原图URL
如果自定义字段保存的是原图完整URL,先通过URL获取附件ID再生成指定尺寸链接:
// 获取自定义字段中的原图URL $original_img_url = get_post_meta(get_the_ID(), 'custom_image', true); $target_size = 'medium_large'; // 替换为目标尺寸名称 if ($original_img_url) { // 通过原图URL获取媒体库附件ID $attachment_id = attachment_url_to_postid($original_img_url); // 优先获取指定尺寸URL,失败则 fallback 到原图 $image_url = $attachment_id ? wp_get_attachment_image_url($attachment_id, $target_size) : $original_img_url; // 输出示例(按需调整) echo '<img src="' . esc_url($image_url) . '" alt="' . esc_attr(get_the_title()) . '">'; }
关键说明
- 替换代码中的
custom_image为你实际使用的自定义字段键名 - 将
medium_large替换为你需要的图片尺寸名称(确保该尺寸在WordPress后台已配置) - 用
esc_url()和esc_attr()处理输出,保障站点安全
内容的提问来源于stack exchange,提问作者Ahmed T
相关产品推荐
相关产品推荐

