Filter the entire document generated by WordPress

Last Updated: April 20, 2019

WordPress provides a vast array of filters with which you can modify the content that gets written to the generated HTML; many theme and plugin authors introduce additional filters of their own.

While you can readily filter primary post or page content with the_content, what happens if you need to filter the entire output generated by WordPress?

This has come up from time to time and for various reasons. In one scenario, I wanted to perform a search and replace of <img /> attributes to provide for lazy-loading with a third-party Javascript library. More recently, a client wanted to replace the itemprop and itemtype schema.org attribute markup generated by a page builder, in order to provide their own in a more finely-tuned fashion.

While I can’t claim to have tested this code exhaustively, it’s held up well in every situation thus far. Just drop it in your functions.php or custom functionality plugin.

Note that in the below example, I was confident that a regex would do the job since a single, well-written plugin was generating the attributes in a consistent fashion. However, generally speaking, it can be dangerous to depend upon a regex to match HTML since formatting can vary widely.

add_action( 'init', 'process_post' );

function process_post() {
     ob_start();
}

// WordPress executes wp_ob_end_flush_all() on shutdown with priority 1,
// so we must use 0 or a negative number to step in front of it.
add_action( 'shutdown', function() {

    $final = '';

    $levels = ob_get_level();

    for( $i = 0; $i < $levels; $i++ ) {
        $final .= ob_get_clean();
    }

    echo apply_filters( 'final_output', $final );
}, 0 );

add_filter( 'final_output', function( $output ) {

	// perform any output filtering here
	$output = preg_replace( '/(<[^>]+) itemprop=".*?"/i', '$1', $output );
	$output = preg_replace( '/(<[^>]+) itemscope=".*?"/i', '$1', $output );
	$output = preg_replace( '/(<[^>]+) itemtype=".*?"/i', '$1', $output );

	return $output;

});

Kudos to this post on Stackoverflow for the majority of this code.

Posted in ,

Chris Aram

I'm a developer who specializes in whipping your technology into shape so that it makes your professional and personal life better.