You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求提供替换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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:51:19