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

更新/保存文章时自动补全图片缺失的宽高属性

问题解决:WordPress保存/更新文章时自动补全图片width/height属性

你之前改用save_post钩子无效的核心原因是:

  1. 没有主动获取并更新数据库里的文章内容
  2. 没处理WordPress的自动保存、修订版、权限验证等机制,导致钩子触发时机不对或无操作权限

以下是修改后的完整可用代码:

function add_img_size_on_save($post_id) {
    // 跳过自动保存、修订版,验证权限
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (wp_is_post_revision($post_id)) return;
    if (!current_user_can('edit_post', $post_id)) return;

    // 获取文章原始内容
    $post = get_post($post_id);
    $content = $post->post_content;
    
    // 复用原有的图片匹配逻辑
    $pattern = '/<img [^>]*?src="(https?:\/\/[^"]+?)"[^>]*?>/iu';
    preg_match_all($pattern, $content, $imgs);
    
    foreach ($imgs[0] as $i => $img) {
        // 已有宽高属性则跳过
        if (false !== strpos($img, 'width=') && false !== strpos($img, 'height=')) {
            continue;
        }
        
        $img_url = $imgs[1][$i];
        // 获取图片尺寸(@屏蔽错误,建议对站外图片加超时处理)
        $img_size = @getimagesize($img_url);
        
        if (false === $img_size) {
            continue;
        }
        
        // 替换图片标签,添加宽高属性
        $replaced_img = str_replace('<img ', '<img ' . $img_size[3] . ' ', $imgs[0][$i]);
        $content = str_replace($img, $replaced_img, $content);
    }
    
    // 只有内容变化时才更新,避免无限循环
    if ($content !== $post->post_content) {
        wp_update_post(array(
            'ID' => $post_id,
            'post_content' => $content
        ));
    }
}
add_action('save_post', 'add_img_size_on_save');

关键说明:

  • 权限与触发过滤:跳过自动保存(DOING_AUTOSAVE)、修订版(wp_is_post_revision),确保只有手动保存/更新时才触发,同时验证用户编辑权限,避免非法操作。
  • 内容更新逻辑:必须主动调用wp_update_post将处理后的内容写入数据库,这是你之前代码缺失的核心步骤。
  • 避免无限循环:对比处理前后的内容,只有发生变化时才执行更新,防止wp_update_post再次触发save_post钩子导致死循环。
  • 站外图片优化:getimagesize获取站外图片可能存在超时风险,建议添加超时设置:
    $context = stream_context_create(array('http' => array('timeout' => 3)));
    $img_size = @getimagesize($img_url, false, $context);
    

内容的提问来源于stack exchange,提问作者Recofa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:40:28