Support » Plugin: Gutenberg » Updating a page with custom shortcodes

  • Resolved DaveWP196

    (@davewp196)


    When I attempt to save a page with a custom shortcode, I get the following error message:

    Updating failed. The response is not a valid JSON response.

    Not sure, what it is, but it is definitely linked to my custom shortcode function. Doing a google search, I found the following workaround:

    function myshortcode(){
         ob_start();
    
         <em>My logic for the shortcode</em>
    
         $content = ob_get_contents();
         ob_end_clean();
         return $content;
    }

    Whilst the above solution works, I’ve not seen this solution covered in any official wordpress description of how to code custom shortcode functions. Clearly this solution has implications on all installations, so I think there must be something I am missing….

    • This topic was modified 1 year, 3 months ago by DaveWP196.
    • This topic was modified 1 year, 3 months ago by DaveWP196.
    • This topic was modified 1 year, 3 months ago by DaveWP196.
Viewing 1 replies (of 1 total)
  • Plugin Author Jorge Costa

    (@jorgefilipecosta)

    Hi @davewp196!

    Thank you for sharing this issue with us.

    On the shortcode function documentation https://developer.wordpress.org/reference/functions/add_shortcode/ there is a note that says “Note that the function called by the shortcode should never produce an output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results.”.

    When one does:

    function myshortcode(){ ?>
     <em>My logic for the shortcode</em>
    <?php }

    One is producing output.

    The function should never output anything (e.g: echo). The function should just return a string with the shortcode result. If the function calls other functions that output something a valid solution is using ob_start(); at the start and return ob_get_contents(); at the end.

    I hope this information is useful for anyone reading it.

Viewing 1 replies (of 1 total)
  • The topic ‘Updating a page with custom shortcodes’ is closed to new replies.