WordPress Final Output Filter – part 2 – Create your own WP Filter Hook

So we have created a way to manipulate the content of the whole page before it’s sent to the browser. Now we will create our custom WP filter, to have a more generic solution, that can be used by other plugins and themes as well.

We can create a custom filter hook by using the apply_filters() function of WP. The first argument is the name of the filter, let’s call it “final_output” and the second argument is the content that will be passed to the callback function.

apply_filters('final_output', $content);

Now we can use this filter anywhere within our code. I will test it here, just to prove it works.

function final_output($content)
{
    return apply_filters('final_output', $content);
}

We use the add_filter() function of WP, the filter “final_output” and second the callback function “final_output_test”. And again we change “lorem” to capitals and start and end with an @ sign. And as you can see it works.

add_filter('final_output', 'final_output_test');

Offcourse we can add more filters, so let’s add another that replaces the word “ipsum”. So again we use add_filter, “final_output” and set a callback, like “final_output_test_2”. First argument is the content and we will set all “ipsum” to capitals and start and end with a hash-sign. Let’s have a look on the site. And it works.

add_filter('final_output', 'final_output_test_2');

function final_output_test_2($content)
{
    return str_replace('ipsum', '#IPSUM#', $content);
}

This filter hook can now be used by other plugins and themes as well, just by using add_filter().
If you prefer working with classes and use an OO approach, then watch the next video.

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 apply_filters('final_output', $content);
}
/**
 * Test code
 */
add_filter('final_output', 'final_output_test');

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

add_filter('final_output', 'final_output_test_2');

function final_output_test_2($content)
{
    return str_replace('ipsum', '#IPSUM#', $content);
}

Leave a Reply