WordPress Custom Shortcode Conflicting with Media Library

First, I’m assuming you put the code in the theme functions.php file, and if so, then there should be no direct output echoed in that file:

  • Good:

    <?php // Assume this is wp-content/themes/your-theme/functions.php
    function some_func() {
        echo 'This is a good output; it\'s not a direct output coming from the file.';
        echo 'The output is only displayed when you call the function - some_func().';
    }
    
  • Bad:

    <!-- This is a HTML comment and it's a sample direct output. -->
    <?php // Assume this is wp-content/themes/your-theme/functions.php
    function some_func() {
        echo 'This is a good output; it\'s not a direct output coming from the file.';
        echo 'The output is only displayed when you call the function - some_func().';
    }
    

Secondly, the Site Health performs a test to check if the REST API is accessible (or working good) and if it’s not, which could be because of invalid response, then you’d see the error “The REST API did not behave correctly“. And that’s most likely what’s happening in your case because you got that <!-- Shortcode display testimonials--> at the top of the file (i.e. your functions.php file). So remove that comment and the error should be gone.

Apart from that, another issue in your code is that you need to make sure your shortcode is returning the output and not echoing it. If you echo it, then the output would be displayed at the wrong place (i.e. not where you put the [TestimonialITW] in the post content) and when you update a post having the shortcode, you’d likely see an error that says “Updating failed. Error message: The response is not a valid JSON response.” — because the response contains the output from your shortcode (e.g. HTML tags like the <div class="owl-carousel owl-theme">).

But if you need to echo it, you can use output buffering:

function testimonial_shortcode()
{
    ob_start();             // turn on output buffering
    display_testimonials(); // put the output to the buffer
    return ob_get_clean();  // capture and return the buffer
}
add_shortcode( 'TestimonialITW', 'testimonial_shortcode' );

And that would replace the following:

function testimonial_shortcode()
{
    add_shortcode('TestimonialITW', 'display_testimonials');
}

add_action('init', 'testimonial_shortcode');

Additionally, unless you have registered a custom post status named published, that 'post_status' => 'published' should be 'post_status' => 'publish'.

Leave a Comment