I keep receiving the "Updating failed. The response is not a valid JSON response." when trying to publish or update a page that uses a custom shortcode I made on wordpress.
The shortcode is supposed to display the content of a custom post. Content of the said custom post is made out of a single custom Gutenberg bloc that relies on ACF to input content. I can give you more info on the why and what of that if needed.
When I do a preview, the shortcode works just like intended. But when i try to publish/update the page, the JSON error pops up.
Here's the code of the shortcode :
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');
I tried at first the advice we see online to solve the JSON error like the permalink structure update and remove the .htaccess to force wordpress to regenerate it but it didn't work.
I tried simplifying the content. First by changing the content of my custom gutenberg post to a simple line of text. Then by removing my block from the custom post and just put a single line of text there. None worked, the JSON error kept popping up.
I changed the_content()
by get_the_content()
. This one "solved" the problem as in I can finally publish and update without the JSON error but the code doesn't do what i want anymore which is to display the content of my post. To be precise, get_the_content()
only displays the text I type above or bellow the gutenberg post that actually matters.
I tried displaying my content with echo
but it also results in a JSON error.
So I'm pretty sure now that the_content()
is what causes trouble but I don't know how to make it work without it. This website truly doesn't want me to publish this content!
Thank you in advance for the help you can provide :)
the_content()
writes to the output buffer directly (and thereby invalidates your JSON response, because "arbitrary text followed by JSON", is hardly ever valid JSON.) get_the_content()
returns the content - but it does not apply the the_content
filters, as the the_content()
function does. So you will need to perform that extra step explicitly here, using https://developer.wordpress.org/reference/functions/apply_filters/
The name of the hook is the_content
, and the second parameter is the content that you want to apply the filters registered to that hook on, so in this case what get_the_content()
gave you:
$content = apply_filters('the_content', get_the_content());