Wordpress - Is there a way to read or list wp_head() contents?

I wanted to search-and-replace in the header, but Neither @majick or @Samuel Elh answers worked for me directly. So, combining their answers I got what eventually works:

function start_wp_head_buffer() {
    ob_start();
}
add_action('wp_head','start_wp_head_buffer',0);

function end_wp_head_buffer() {
    $in = ob_get_clean();

    // here do whatever you want with the header code
    echo $in; // output the result unless you want to remove it
}
add_action('wp_head','end_wp_head_buffer', PHP_INT_MAX); //PHP_INT_MAX will ensure this action is called after all other actions that can modify head

It was added to functions.php of my child theme.


Simple solution is to listen for wp_head in a custom function, just like WordPress does in wp-includes/general-template.php for wp_head() function.

I mean something like:

function head_content() {
    ob_start();
    do_action('wp_head');
    return ob_get_clean();
}
// contents
var_dump( head_content() );

Later, use regex or other tool to filter the contents you are targeting..

Hope that helps.


You could buffer the wp_head output by adding some wrapper actions to it:

add_action('wp_head','start_wp_head_buffer',0);
function start_wp_head_buffer() {ob_start;}
add_action('wp_head','end_wp_head_buffer',99);
function end_wp_head_buffer() {global $wpheadcontents; $wpheadcontents = ob_get_flush();}

You can then call global $wpheadcontents; elsewhere to access the content and process it.

But, in this case, it may be simpler to just get the information you are looking for directly from the global $wp_styles and $wp_scripts variables.

function print_global_arrays() {
    global $wp_styles, $wp_scripts;
    echo "Styles Array:"; print_r($wp_styles);
    echo "Scripts Array:"; print_r($wp_scripts);
}
add_action('wp_enqueue_scripts','print_global_arrays',999);

Tags:

Wp Head