WordPress Final Output Filter – part 3 – Refactor to a class (OO)

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.

In this tutorial I will refactor the code from the previous video (part 2) by creating a class.

class FinalOuputFilter
{

    public function __construct()
    {
        ob_start(array($this, 'final_output'));
    }

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

}
$finalOutput = new FinalOuputFilter();
(new FinalOuputFilter());
    public static function create()
    {
        $instance = new FinalOuputFilter();
        return $instance;
    }
FinalOuputFilter::create();

Result Plugin Final Output Filter

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

class FinalOuputFilter
{

    public static function create()
    {
        $instance = new FinalOuputFilter();
        return $instance;
    }

    public function __construct()
    {
        ob_start(array($this, 'final_output'));
    }

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

}

// create instance
FinalOuputFilter::create();

Leave a Reply