如何通过 wordpress API 端点 return <head> 中的内容

How to return content in <head> through a wordpress API endpoint

所以我一直在尝试扩展 Wordpress API 以获取 Wordpress 在 <head> 中输出的内容。

我已经在我的主题 functions.php 中像这样注册了我的端点:

add_action('rest_api_init', function () {
  register_rest_route( 'hs/v1', 'header',array(
                'methods'  => 'GET',
                'callback' => 'get_head_content'
      ));
});

回调如下所示,但每个键只有 returns 个空数组:

function get_head_content() {

    $result = [];
    $result['scripts'] = [];
    $result['styles'] = [];

    // Print all loaded Scripts
    global $wp_scripts;
    foreach( $wp_scripts->queue as $script ) :
       $result['scripts'][] =  $wp_scripts->registered[$script]->src . ";";
    endforeach;

    // Print all loaded Styles (CSS)
    global $wp_styles;
    foreach( $wp_styles->queue as $style ) :
       $result['styles'][] =  $wp_styles->registered[$style]->src . ";";
    endforeach;

    return $result;
}

所以我的猜测是 get_head_content returns 什么都没有,因为没有任何东西被排队,因为我实际上并没有通过点击 API 端点来触发队列。这并没有真正将整个 <head> 输出为字符串,这将是我的主要 objective.

有人知道如何实现吗?

感谢您的帮助!

您可以使用输出缓冲区和get_header:

function get_head_content() {
    ob_start();
    get_header();
    $header = ob_get_contents();
    ob_end_clean();

    return $header ;
}