How to make an WordPress plugin from scratch
Filed Under (php, wordpress) by The Chef on 03-07-2009
Tagged Under : php, regex, wordpress, wordpress plugin
<?php
/*
Plugin Name: My-plugin
Plugin URI: http://ezbitz.com/
Description: Remove all links from comments
Version: 1.0
Author: The Chef
Author URI: http://ezbitz.com
*/
function clean_comments($text)
{
return preg_replace ( '%<a[^>]*>(.*?)</a>%si', '$1', preg_replace ( '/\b(https?)(:\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i', 'hxxp$2', $text ) );
}
add_filter ( 'comment_text', 'clean_comments' );
?>
Create an empty php file. First of all we need to fill some plugin details that will appear on the plugins page: plugin name, description, author, version etc.
For this example I’ve decided to make a small plugin that removes the links from comments. For this, we need to hook the wordpress function that displays comments from the database. For an in-depth analisys of a plugin writing, go to http://codex.wordpress.org/Writing_a_Plugin. Let’s go back to our hooks: the hook that deals with the comments retrival is “comment_text”, so we set the hook on this function. In other words, after the comment content is retrieved from the database and before it is sent to browser, our function is called, here
function clean_comments($text)
Inside this function we use 2 cascaded regex in order to remove link tag and replace http with hxxp. This take only one line of code. I know this isn’t so elegant but for the artistic effect it works:) .
And that’s our plugin.
Make a directory inside wp-content/plugins and copy php file there. Go to plugin administration panel and whatch your plugin there !