So I've been trying to extend the Wordpress API to fetch the content which Wordpress outputs in the <head>
.
I've registered my endpoint like so in functions.php
of my theme:
add_action('rest_api_init', function () {
register_rest_route( 'hs/v1', 'header',array(
'methods' => 'GET',
'callback' => 'get_head_content'
));
});
And the callback looks like below but only returns empty arrays for each key:
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;
}
So my guess is that the get_head_content
returns nothing since nothing has been enqueued because I'm not actually triggering the queue by hitting the API endpoint. This doesn't really output the whole <head>
as a string either which would be my main objective.
Does anyone know how to achieve this?
Appreciate the help!
You can use the output buffer and get_header:
function get_head_content() {
ob_start();
get_header();
$header = ob_get_contents();
ob_end_clean();
return $header ;
}