
When you are writing a plugin, does it ever bother you that there are occasions when you need to add a hook, to call a function, to call another function? Menus are a good example. In some other blogging systems it isn’t necessary to manually add the hook itself, and you can emulate that quite easily in WordPress.
Here’s a quick example that shows a way of automatically creating hooks, and also gets that functionality out of the way so you are free to concentrate on your plugin.
First create a class. I have called it plugin, but you will need to choose something unique to make sure it doesn’t conflict. Use this code:
[php]
class plugin{
public function __construct(){
$methods = get_class_methods($this);
foreach($methods as $method){
if ( is_int( strpos($method , 'filter') ) ){
$filter_name = str_replace('filter_' , '' , $method);
add_filter( $filter_name , array($this,$method) );
} elseif ( is_int( strpos($method , 'action') ) ){
$filter_name = str_replace('action_' , '' , $method);
add_action( $filter_name , array($this,$method) );
}
}
if( method_exists($this,'init') ){
$this->init();
}
}
}
What this does is quite simple. When the class is instantiated it gets a list of the methods and checks each one for the prefixes, filter, and action. If it finds a function with one of those names it chops the prefix off and registers the rest as a hook.
For example: A method with the name filter_the_content, would be registered as a filter using the_content hook.
Finally, it checks to see if the class has a method called init and if it does it runs it.
To use this you need to extend it. The following example shows how to filter the content:
[php]
class ed_balls extends plugin {
function filter_the_content($content){
return "Ed Balls";
}
}
This replaces your content with the words, “Ed Balls”. Not useful in itself but it serves as an example.
If you still wanted to use some hooks manually, perhaps you want to set the priority, or change the number of arguments passed you can use the init function and treat it as thought it were the constructor.
For example:
[php]
class ed_balls extends plugin {
function init(){
add_action('wp_footer',array($this,'add_footer'),1);
}
function add_footer(){
echo "a footer";
}
}
(__)
`
I really like the idea. You should consider making “plugin” an abstract class.
(__)
`
That's a good point wesley. The other option that I considered was to do as Habari does and have a specific function to add all the priorities into an array so the constructor can handle them. I wanted to keep it very simple though. I might expand the post tomorrow to include that.
(__)
`
Very nice, only issue is, for the custom priority etc, your function can no longer have the name action_add_footer, which is inconsistent with the rest of the function names.
Perhaps better would be to have an array of these special functions that should be ignored by the constructor.