Admin first hook that outputs HTML?

I think load-(page) is the first hook in the admin screen that deals with outputting HTML, but I’m not totally sure. Basically I’m looking for the equivalent to template_rediect or get_header, which don’t work on the admin side (correct me if I’m wrong).

I’d like to hook into every admin page. My guess using either $page_now or get_current_screen() but my mind is going blank on how I’d implement them on all pages:

$page = get_current_screen()->parent_file;
add_action( 'load-$page.php', 'add_action_all_load_hook', 1, 0 );

On the front-end I would do this:

function link_rel_buffer_callback($buffer) {
    $buffer = preg_replace('ORIGINAL', 'NEW', $buffer);
    return $buffer;
}

function link_rel_buffer_start() {
    ob_start("link_rel_buffer_callback");
}
function link_rel_buffer_end() {
    ob_flush();
}
add_action('template_redirect', 'link_rel_buffer_start', -1);
add_action('get_header', 'link_rel_buffer_start');
add_action('wp_footer', 'link_rel_buffer_end', 999);

I’m thinking the equivalent would be

add_action('load-$page', 'link_rel_buffer_end', 1, 0);
add_action('in_admin_footer', 'link_rel_buffer_end', 999);

but I can’t grasp how to do load-(page) on every load.

// UPDATE BASED ON @birgire example

add_action( 'admin_init', 'wpse_admin_init' );
function wpse_admin_init( $buffer )
{
    if( ! defined( 'DOING_AJAX') || ! DOING_AJAX )
        ob_start( 'wpse_buffering' );
}

function wpse_buffering( $buffer )
{   
    $buffer = preg_replace('FIND', 'REPLACE', $buffer);
    return $buffer;
}


function wpse_buffering_shutdown() {
        ob_flush();
    }
add_action('in_admin_footer', 'wpse_buffering_shutdown', 9999);

1 Answer
1

You can try this one:

/**
 * Fires as an admin screen or script is being initialized.
 *
 * Note, this does not just run on user-facing admin screens.
 * It runs on admin-ajax.php and admin-post.php as well.
 *  
 * This is roughly analgous to the more general 'init' hook, which fires earlier.
 *
 * @since 2.5.0
 */
do_action( 'admin_init' );

if you need a hook activated on every admin page.

For example:

add_action( 'admin_init', 'wpse_admin_init' );

function wpse_admin_init( $buffer )
{
    if( ! defined( 'DOING_AJAX') || ! DOING_AJAX )
        ob_start( 'wpse_buffering' );
}

function wpse_buffering( $buffer )
{       
    return $buffer;
}

ps: If you need to hook into the part after </html>, you can use the PHP function register_shutdown_function() to run your own callback after the PHP script has finished executing. But notice that then the output buffers have already be sent to the client, according to this comment on the PHP docs.

Leave a Comment