WordPress Final Output Filter – part 1 – Filter the whole page

WordPress contains certain filter hooks for filtering the content, like post title, post content, text widgets etcetera, but it doesn’t contain a hook for filtering the whole page. And sometimes it can be useful to have such a filter. In this tutorial I will show you how.
First I will show you just how to filter the whole page. Then I will show a general solution by creating a custom WP hook. That way the hook can also be used by other plugins and themes. And finally I will show you how the create it using a class.

We make a new plugin by creating a new file in the plugins folder of your WordPress installation. It contains a simple header with plugin name, version, description and author.

/*
Plugin Name:    Final Output Filter
Version:        0.1.0
Description:    Demo Plugin Development Tutorial
Author:         Victor Villaverde Laan
*/

Now can use the PHP function ob_start() . All output after this function call will not be outputted immediately but first stored in a buffer. That means we can manipulate the output before it’s sent to the browser. One way to manipulate the output is to set a callback as first argument of the function. This works just the same as adding a callback to the add_action or add_filter function of WordPress. In this case we will add a global function as a callback, let’s call it “final_output”.

ob_start('final_output');

Then we create the function. The first argument of this function will be the content that’s stored in the buffer. So the output that has not yet been sent. Now we can change the content and need to return the new content. If we just return the content input, nothing will be changed.
In this example we will change the word “lorem” to “LOREM” with capitals and put a @ sign at the beginning and at the end.

function final_output($content)
{
    return str_replace('lorem', '@LOREM@', $content);
}

Let’s have a look at the site. As you can see this post contains some “lorem ipsum” text. When we activate our created plugin in the admin part. And go back to the site and refresh the page, you will see all “lorem” texts have been replaced on the whole page, also in the site title.
But this is very specific code, we’ll have to repeat in every plugin and theme we want to use this. It would be better to create a more general solution, by creating a custom filter in WordPress. In the next tutorial I will show you how.

Result

<?php
/*
Plugin Name:    Final Output Filter
Version:        0.1.0
Description:    Demo Plugin Development Tutorial
Author:         Victor Villaverde Laan
*/

ob_start('final_output');

function final_output($content)
{
    return str_replace('lorem', '@LOREM@', $content);
}

Leave a Reply