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

如何阻止WordPress修改我的短代码区块?

WordPress短代码输出自动插入
/空

标签的解决办法


1. 短代码内部临时禁用wpautop

wpautop默认优先级是10,大概率是它在短代码输出后额外做了格式化处理。直接在短代码函数里临时关闭它,输出完成后再恢复:

function custom_header_shortcode() {
    // 临时移除wpautop过滤
    remove_filter('the_content', 'wpautop');
    ob_start();
    // 这里放置你的HTML和PHP代码
    ?>
    <!-- 你的短代码内容 -->
    <?php
    $output = ob_get_clean();
    // 恢复wpautop过滤
    add_filter('the_content', 'wpautop', 10);
    return $output;
}
add_shortcode('header', 'custom_header_shortcode');

2. 给短代码区块单独禁用格式化

你用的是core/shortcode区块,WordPress更新后可能区块编辑器对这类区块的输出新增了自动格式化逻辑。在functions.php中添加以下代码,让短代码区块跳过wpautop处理:

add_filter('block_type_metadata_settings', function($settings, $metadata) {
    if ($metadata['name'] === 'core/shortcode') {
        $settings['render_callback'] = function($attributes, $content) {
            remove_filter('the_content', 'wpautop');
            $output = do_shortcode($content);
            add_filter('the_content', 'wpautop', 10);
            return $output;
        };
    }
    return $settings;
}, 10, 2);

3. 给短代码输出添加“免格式化标记”

给短代码的输出前后加上特定注释,再通过过滤函数让wpautop忽略这段内容:

首先在functions.php中添加过滤逻辑:

add_filter('the_content', function($content) {
    // 匹配标记内的内容,跳过wpautop处理
    $content = preg_replace_callback('/<!-- no-autop -->(.*?)<!-- \/no-autop -->/s', function($matches) {
        return $matches[1];
    }, $content);
    return $content;
}, 9); // 优先级设为9,比wpautop的10提前执行

然后修改短代码函数,给输出套上标记:

function custom_header_shortcode() {
    ob_start();
    // 你的HTML和PHP代码
    ?>
    <!-- 你的短代码内容 -->
    <?php
    $output = '<!-- no-autop -->' . ob_get_clean() . '<!-- /no-autop -->';
    return $output;
}

4. 模板文件中临时禁用wpautop

如果该短代码仅在index模板中使用,可以直接在模板输出短代码的前后操作:

// 输出短代码前移除wpautop
remove_filter('the_content', 'wpautop');
// 输出短代码
echo do_shortcode('[header]');
// 输出完成后恢复wpautop
add_filter('the_content', 'wpautop', 10);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:55:04