How to create a WordPress content filter plugin?

It is pretty easy to roll out a WordPress plugin that adds a content filter.

Creating a WordPress content filter plugin

Here are the basic steps to replace the content with a filter. This example is very rudimentary and replaces all of the content, which you would probably never really do.

  1. Create a new file called MyPlugin.php
  2. Add this code:
    [php]
    <?php
    /*
    Plugin Name: <Your Plugin Name>
    Version: 1.0
    Plugin URI: tba
    Description:
    Author: <your name>
    Author URI: <your web site>
    */

    function handleContentFilter( $content = null ) {
    return "Hello, World!";
    }

    $test = add_filter( "the_content", "handleContentFilter" );

    ?>
    [/php]

  3. Upload (or copy) MyPlugin.php to the /wp-content/plugins/ directory in your WordPress install.

Replace content based on a search string

This is more likely what you are going to do. Sames steps as above, but change the file as follows:

[php]
function handleContentFilter( $content = null ) {
return str_replace("FindMe","Hello, World!", $content);
}
[/php]

Using a WordPress shortcode plugin

  1. Start a new Post
  2. type in the following:

    FindMe

  3. Click Preview.

Your post should have replaced FindMe with “Hello, Word!”.

A better WordPress content filter plugin template

While the above is all you need, a more scalable solution might involve using classes. Here is a template that uses classes.

[php]
<?php
/*
Plugin Name: <Your Plugin Name>
Version: 1.0
Plugin URI: tba
Description:
Author: <your name>
Author URI: <your web site>
*/

// A class to manage your plugin
class MyPlugin {

public function MyPlugin( $shortCodeHandler ) {
$result = add_filter( ‘the_content’, array( $shortCodeHandler, ‘handleContentFilter’ ) );
}

}

// A class to handle your shortcode
class ContentFilterHandler {

public function handleContentFilter( $content = null ) {
return str_replace("FindMe","Hello, World", $content);
}

}

$contentFilterHandler = new ContentFilterHandler();
$plugin = new MyPlugin( $contentFilterHandler );

?>
[/php]

Leave a Reply

How to post code in comments?

*