Headers 已在 REST API 调用中使用 get_template_part 发送错误

Headers already sent error with get_template_part in REST API call

我已经查看了有关此警告的多个其他问题(Headers 已发送...等)和 this thorough explanation,但我没有找到适合我的情况的解决方案处理:

  1. 我有一个自定义 Wordpress REST API 端点,returns get_template_part 的输出。当我在页面上正常调用 get_template_part 时,没有任何警告。它仅在 register_rest_route 的回调中运行时出现。
  2. 我还使用 this library 从外部 API 获取数据。当我开始提出这些请求时,错误就开始了。我已经尝试在模板部分内部和外部发出请求,后者在 register_rest_route 的回调中或作为 init 操作。
  3. 触发错误的行是一个 img 标签,我在这里 echo-ing URL 作为 src 使用来自外部 API回应。此模板中还有其他 echo 个调用,所以我怀疑这是问题所在。
  4. 有问题的线路实际上工作正常并且完成了它的工作。我只需要摆脱该死的警告。

代码:

里面 functions.php:

<?php

  //the api endpoint declaration
  add_action( 'rest_api_init', function () {
    register_rest_route(
        'theme/v2',   // namespace
        '/homepage',  // route
        array(                  // options
            'methods'  => 'GET',
            'callback' => 'build_home',
        )
    );
  });

  //the callback for the wordpress api
  function build_home() {

    // this is the external API request, using their PHP library. 
    // I linked the library above. The request returns an object with a bunch of data
    include_once(get_template_directory()."/arena/arena.php");
    $arena = new Arena();
    $page = $arena->set_page(); 
    $per = 8; 
    $slug = 'concepts-bo-6ajlvpqg'; 
    $channel = $arena->get_channel($slug, array('page' => $page, 'per' => $per));

    //I'm passing the response from the external API (in $channel) to get_template part
    //get_template_part is then the output for the wordpress API request
    get_template_part('custom-home-template',null,array('channel'=>$channel));
 }

 ?>

内部模板部分:

<?php
  $channel=$args["channel"];
  ?>

  <div id="concepts-box" class="bodycontent reg-width">
    <?php foreach ($channel->contents as $item) { if($item->class=="Image"){
      $img=$item->image["square"]["url"];
      ?>
    <div class="concept-wrapper">
      <!-- the line below is the one that triggers the error -->
      <img lozad src="<?=$img; ?>">
    </div>
    <?php }} ?>
  </div>

完全警告:

<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /filepath/wp-content/themes/theme/custom-home-template.php:63) in <b>/filepath/wp-includes/rest-api/class-wp-rest-server.php</b> on line <b>1372</b><br />

在 Wordpress SO 上回答 — link here。问题是我将 get_template_part 视为 API 响应,而不是通过输出缓冲将其馈送到变量