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

WordPress自定义短代码发布更新时出现无效JSON响应错误求助

问题:WordPress自定义短代码引发发布/更新JSON响应错误

在使用自定义短代码展示blocschiffres类型自定义文章内容时,发布或更新页面会弹出错误提示:Updating failed. The response is not a valid JSON response.。该自定义文章由依赖ACF的单个Gutenberg区块构成,预览时短代码功能正常,但发布/更新操作必触发上述错误。

原短代码代码

function signature_bloc_sst(){
    
    $args = array(
        'post_type' => 'blocschiffres',
    );
    
    $query = new WP_query($args);
    
    if($query->have_posts()) :
    
        while($query->have_posts()) :
    
            $query->the_post();
    
            $content = the_content();
        
        endwhile;
    
        wp_reset_postdata();
    
    endif;
    
    return $content;
}

add_shortcode('bloc-sst', 'signature_bloc_sst');

已尝试的无效方案

  • 更新固定链接结构
  • 删除.htaccess文件让WordPress重新生成
  • 将自定义文章内容简化为纯文本或移除自定义区块

替换the_content()为get_the_content()后,发布/更新不再报错,但无法正常渲染Gutenberg区块内容,仅能显示区块前后的文本;使用echo输出内容同样会触发JSON错误。


原因分析

the_content()函数的特性是直接输出内容而非返回内容,当WordPress后台执行保存操作时,短代码中的直接输出会打乱请求的JSON响应结构,导致返回结果不符合JSON格式,从而触发错误。而get_the_content()仅获取原始内容,不会触发Gutenberg区块的渲染钩子,因此无法正确显示区块内容。


解决方案

使用apply_filters('the_content', get_the_content())获取经过所有过滤器处理后的完整内容(包括Gutenberg区块的渲染逻辑),同时确保内容以返回方式传递,避免直接输出。

修改后的短代码

function signature_bloc_sst(){
    $content = '';
    $args = array(
        'post_type' => 'blocschiffres',
    );
    
    $query = new WP_Query($args);
    
    if($query->have_posts()) :
        while($query->have_posts()) :
            $query->the_post();
            // 通过过滤器获取渲染后的完整内容,替代直接输出的the_content()
            $content .= apply_filters('the_content', get_the_content());
        endwhile;
        wp_reset_postdata();
    endif;
    
    return $content;
}
add_shortcode('bloc-sst', 'signature_bloc_sst');

关键说明

  • apply_filters('the_content', get_the_content())会触发所有针对the_content的过滤器,包括Gutenberg区块的渲染逻辑,确保ACF自定义区块能正常显示。
  • 初始化$content为空字符串,避免无文章时返回未定义变量。
  • 修正WP_query为规范的驼峰式写法WP_Query(WordPress函数名大小写不敏感,但规范写法更易维护)。

内容的提问来源于stack exchange,提问作者Naël Soufi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:40:27