cURL External API request displays content above other content on page

Excerpt from the Shortcode API handbook (italic formatting added by me):

The return value of a shortcode handler function is inserted into the
post content output in place of the shortcode macro. Remember to
use return and not echo – anything that is echoed will be output to the browser, but it won’t appear in the correct place on the page
.

So the issues in question (misplaced output and JSON responses error) happened because you used echo $response; instead of return $response; in your shortcode handler function, i.e. picts_ct_responses().

And to fix the issues, all you need to do is simply replace that echo with return and the error would be gone.


Additionally, WordPress provides various helper functions like wp_remote_get() for making HTTP requests to an external service/API/website, so you should use those helper functions instead of manually calling cURL functions like curl_setopt().

And you’d also would want to cache (e.g. using the Transients API) the responses received from your HTTP requests for performance reasons, particularly in the case of shortcodes which can be automatically called multiple times on the same page.