Skip to content
Advertisement

Headers already sent error with get_template_part in REST API call

I’ve looked at multiple other questions about this warning (Headers already sent…etc) and this thorough explanation, but I’m not finding a solution for the circumstances I’m dealing with:

  1. I have a custom WordPress REST API endpoint that returns the output of get_template_part. When I just call get_template_part normally on a page, there’s no warning. It only appears when it runs in register_rest_route‘s callback.
  2. I am also fetching data from an external API using this library. The error started when I started making these requests. I’ve tried making the request both inside and outside the template part, the latter either within register_rest_route‘s callback or as an init action.
  3. The line that triggers the error is an img tag, where I’m echo-ing a URL as the src using data from the external API response. There are other echo calls all over this template, so I doubt that’s the issue.
  4. The line in question actually works fine and does its job. I just need to get rid of the accursed warning.

Code:

Inside functions.php:

JavaScript

Inside template part:

JavaScript

Full warning:

JavaScript

Advertisement

Answer

Answered on WordPress SO — link here. The issue was I was treating get_template_part as an API response instead of feeding it through output buffering into a variable

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement