How to Create a WP Plugin to change/add/filter Post Content

Plugins are a nice way to add wordpress functionality without changing the existing codebase or the existing theme. There are zillions of wordpress plugins, but sometimes the fastest solution to add a simple functionality is to create your own.

One of the easiest plugins to create is one which alters the post content. There is no admin panel for it, everything is contained and once is activated it magically alter the content for a post before being displayed.

In order to install a plugin, first you have to copy it inside wordpress plugins folder(wordpress can do it for you if you install a plugin from the wordpress repository via Admin panel). Then in order to be used by wordpress you need to activate it. Once done the plugins becomes effective an it does what is supposed to do. Plugins which are not activated do not interact with the wordpress installation, they are only displayed in the wordpress plugins section in the Admin panel.

Plugin files must be placed in the installation structure, inside wp-content/plugins, in a self containing subdirectory with the same name as the main plugin file. If the plugin consist of a single file it can also be placed directly in the plugins folder, but it’s not recommended.

In our example the plugin file is myplugin.php. We need to add a comment header in which we specify a few parameters which are used by wordpress when it displays the plugin info

First of all we have to invoke the wordpress add_filter hook function. This function informs wordpress that before the content is displayed it should first invoke the method we indicated as parameter:

The we have to define the function which does a very simple thing: it adds to the content a simple string. There is also the condition to check that the content does not belong to a feed or a page and is the single post, not in a loop of several posts( like the main page a category page ).

Now we have the entire plugin written, in few lines: a header section, adding a hook to wordpress and implementing the hook. This snippet can be used to display social network buttons like facebook and twitter before or after the posts, to insert ads or to enhance the post with fancy js code.

Leave a Reply

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