This is probably a PHP fundamental, so apologise if I'm stupid in advance.

I'm building a simple plugin for Wordpress which accesses wp_head, grabs the code block (scripts and styles) and then returns this code via an API call (Wordpress Rest API). In order to access this code, the example API call would be made via a GET to

The function in this script end_wp_head_buffer() is producing the code block as a string (I've var_dump it and the code appears OK in the HTML head in browser tools), but when I try to pass this code block to rest_ensure_response function, it sends back NULL.

I'm thinking that it's probably rest_ensure_response running before $the_code is set?

Any help you can offer would be greatly appreciated! Thanks.

// create the routes and endpoints for this plugin
function get_endpoint_code() {

    // call and stringify the contents of wp_head
    function start_wp_head_buffer() {

    function end_wp_head_buffer() {
        $the_code = ob_get_clean();
        $the_code = json_encode($the_code);
        return $the_code;

    add_action('wp_head','end_wp_head_buffer', PHP_INT_MAX);

    return rest_ensure_response($the_code);

function register_route() {
    register_rest_route( 'custom-api/v1', '/code', array(
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'get_endpoint_code',
    ) );

add_action( 'rest_api_init', 'register_route' );

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.