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

如何从WordPress中清理未使用的Visual Composer短代码?

原代码存在的问题
  • 误判在用短代码:原代码依赖全局$shortcode_tags数组判断有效短代码,但WPBakery(原Visual Composer)的部分短代码是动态注册的,或未完全写入该数组,导致在用的VC短代码被误判为“未使用”而被删除。
  • 正则匹配逻辑缺陷:正则中的负向断言(?!$tagregexp)位置错误,可能匹配到短代码标签的中间字符,导致正常短代码被错误匹配清理。
  • 清理范围失控:代码会清理所有未被WordPress识别的短代码,而非仅针对VC系列短代码,容易误删其他插件或自定义短代码。
仅清理前端未使用VC短代码的解决方案

我们可以针对性地只处理vc_开头的短代码,且仅在前端页面执行清理,同时避免影响后台编辑:

方案1:指定要清理的VC短代码列表(最安全)

如果明确知道哪些VC短代码不再使用,直接列出目标短代码进行精准清理:

add_filter('the_content', 'clean_unused_vc_shortcodes_frontend', 99);
function clean_unused_vc_shortcodes_frontend($content) {
    // 仅在前端执行,后台编辑时不处理
    if (is_admin()) {
        return $content;
    }

    // 定义要清理的VC短代码列表
    $unused_vc_tags = [
        'vc_row',
        'vc_column',
        'vc_column_text'
        // 可添加其他需要清理的VC短代码
    ];

    foreach ($unused_vc_tags as $tag) {
        // 清理自闭合和带闭合标签的短代码
        $content = preg_replace('/\[' . preg_quote($tag, '/') . '.*?\]/s', '', $content);
        $content = preg_replace('/\[' . preg_quote($tag, '/') . '.*?\].*?\[\/' . preg_quote($tag, '/') . '\]/s', '', $content);
    }

    return $content;
}

方案2:自动检测未注册的VC短代码

如果不确定具体哪些短代码未使用,可以检测vc_开头且未注册的短代码,仅在前端清理:

add_filter('the_content', 'clean_unregistered_vc_shortcodes_frontend', 99);
function clean_unregistered_vc_shortcodes_frontend($content) {
    if (is_admin()) {
        return $content;
    }

    global $shortcode_tags;
    // 匹配所有vc_开头的短代码
    preg_match_all('/\[\/?vc_[a-zA-Z0-9_]+.*?\]/s', $content, $matches);

    if (!empty($matches[0])) {
        foreach ($matches[0] as $shortcode) {
            // 提取短代码标签名
            preg_match('/vc_[a-zA-Z0-9_]+/', $shortcode, $tag_match);
            if (!empty($tag_match[0]) && !isset($shortcode_tags[$tag_match[0]])) {
                // 清理未注册的VC短代码
                $content = str_replace($shortcode, '', $content);
            }
        }
    }

    return $content;
}

注意事项

  • 优先使用方案1,精准清理更安全,避免误删仍在使用的短代码。
  • 代码添加到主题的functions.php文件,或使用自定义代码插件。
  • 操作前建议备份站点和数据库,避免意外问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 07:54:10