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

如何在WordPress指定自定义文章类型内容区的所有图片外围添加div包裹

实现方案(针对WordPress环境)

该方案通过WordPress原生the_content过滤器实现,仅作用于指定自定义文章类型的前端内容输出,不会修改数据库存储的原始内容。

可直接使用的代码

将以下代码添加到你当前使用主题的functions.php文件,或者自定义功能插件的代码文件中即可:

add_filter('the_content', 'wrap_cpt_images_with_div');
function wrap_cpt_images_with_div($content) {
    // 替换为你自己的自定义文章类型slug
    $target_cpt_slug = 'your_custom_post_type';
    // 仅对指定自定义文章类型的详情页生效
    if (get_post_type() === $target_cpt_slug && is_singular($target_cpt_slug)) {
        // 匹配内容中所有img标签
        $pattern = '/<img([\w\W]+?)\/?>/i';
        // 可自定义外层div的类名,按需修改custom-image-wrapper即可
        $replacement = '<div class="custom-image-wrapper">$0</div>';
        $content = preg_replace($pattern, $replacement, $content);
    }
    return $content;
}

补充说明

  • 自定义文章类型的slug可以在CPT注册代码、后台CPT列表页的URL参数中找到
  • 如果需要排除带特定类的图片不做包裹,可修改正则规则,例如要排除带no-wrap类的图片,可将$pattern改为/<img(?!.*class=".*no-wrap.*")([\w\W]+?)\/?>/i
  • 代码部署后可先清空缓存再预览效果,确认无误后正式上线即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:57:02