Menu

Assign functions to hooks

Akram Deshwali

Assign functions to hooks

Ok now the fun part begins ! You know how to find hooks you know how to read their name but how to use them ?
To do that we need to go back to our demo_plugin.php file where all we have till now is the demo_info() function. Now we need to make another function that will actually do something (example show a text). We are going to name it demo_do_stuff(), we added the demo prefix just to make sure that it is unique.

<?php
function demo_do_stuff(){
echo "I am executed here !";     
}
?>

We added the function definition now we need a place to execute it. Just for the sick of the example we open /header.php file and we read some hooks from there. The first one we see is the header_top hook. It's placed at the very top of the header.php file and it's before the include of the tpl file so our function should echo the data before the To add that address in the plugin file we do this
$plugins->add_hook("header_top","demo_do_stuff");
The first argument represents the name of the hook and the second one the name of the function that you want to executed where that hook is called by run_hook() or grab(). Now go to Admincp → Plugin Manager and make sure your plugin is activated. If you did everything right your plugin should look like this If you have a look on your site you should see something like this.

If you have a look on the site source you will see

Well you just made your first plugin that wasn't that hard was it? Feel free to experiment with different names of the hooks. You can also do this $plugins->add_hook(“header_top”,“demo_do_stuff”); $plugins->add_hook(“header_end”,“demo_do_stuff”); and you should get this

Now that type of functions work for hooks taken from run_hook(). If you get the hook name from grab() function you function needs to look like this

<?php
 function demo_do_stuff($value) {
     // do something with $value
     return $value;
     // $value will be the content of the tpl file
 }
 ?>

If you want to be safe in all the situations you can use the next structure to all the hooks no matter if they pass any argument or not
<?php
function demo_do_stuff($value='') {
// do something
// this will work for any type of hook :)
return $value;
}
?>
You can obviously add as many functions and hooks as you want in your plugin. But be careful. Too many functions can slow down your site. Now lets try [Adding Settings] to our plugin.


Related

Wiki: AD AutoIndex Plugins Documentation