WordPress filter function to modify final html output

WordPress has great filter support for getting at all sorts of specific bits of content and modifying it before output. Like the_content filter, which lets you access the markup for a post before it’s output to the screen.

WordPress also have action hook that fires just before PHP shuts down execution.

do_action( 'shutdown' )

By adding function to this action hook, it is possible to change anything. The following will code work.

rs the entire WP process, capturing the final output for manipulation.
 */

ob_start();

add_action('shutdown', function() {
    $final = '';

    // We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting
    // that buffer's output into the final output.
    $levels = ob_get_level();

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

    // Apply any filters to the final output
    echo str_replace('foo', 'bar', $final);
}, 0);

The code go to functions.php in your theme’s file.

If you need any help with code, feel free to comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *