Introduction to WordPress Filter API Functions
add_filter( $component, $function);
add_filter function has 2 required attributes and 2 optional attributes. Since this post is meant to create a very basic plugin I’m only using the 2 required attributes. First parameter is the wordpress component you want to filter. This can be your post content,title..etc. For each of these types wordpress has a predefined tag. For example if you want to filter the post content, the_content method should be used for the component part. Next parameter is the php function which is used to filter the content.
add_filter(the_content, sample_function);
Writing a Simple WordPress Plugin
/* Plugin Name: Simple Ad Plugin URI: - Description: Adds a advertisement image on every blog post. Version: 1.0 Author: nimeshrmr Author URI: www.innovativephp.com */
- Plugin name should be a unique one for your wordpress installation. 2 plugins with same name will make the system conflict.
- You can include a plugin uri if your plugin is hosted in a public place.
- Description about the functionality of your plugin.
- Version number of your plugin.
- Name of the person who created the plugin.
- Url of the website of the author.
Now we can start writing the plugin code. First create a php function as shown below and call the function using the add_filter function.
function displayAd($content){
return $content.'<img src="ad.jpg" />';
}
add_filter('the_content', 'displayAd');
Above code contains a simple plugin function which adds a advertisement image after every post. $content variable passed to the displayAd method contains the actual blog post text. displayAd function is added as a filter to the blog post content using the wordpress the_content method. You can make the image appear first by concatenating content to image instead of image to content.
This example shows you how to make a simple filters to your content. You can create plugins like post rating,post commenting,post views using the above method. Also you can use filters like the_title,the_tags instead of the_content method, according to your requirement.
Installing and Activating your WordPress Plugin
- Create a folder with the plugin name and include all the code scripts inside the folder.
- Copy the folder to plugins directory inside the wp-content folder in your wordpress installation.
- Log in as admin and click menu item called plugins in the left sidebar.
- Plugin will be listed with your provided details and click activate to activate the plugin.
- Now every time a blog post is loaded your plugin function will be executed and displayed in the browser.
