Basic plugin development

  • Hooks
  • actions and filters

Hooks in wordpress

in wordpress, when some point in the execution is going on a hook is emitted like when the user created a new post or when the user logs out.

We can write code that will be attached to these hooks and executed when hooks are called.

There are two types of hooks in wordpress

  1. Action hook
  2. Filter hook

Action Hooks

Action hook let’s us do something when the hook gets called.

For example we can remove all data of our plugin when the uninstall action is called.

Action hooks are defined using

do_action( 'action_name', [optional_arguments] );

We can then execute some code by attaching a function to this action hook

add_action('action_name' , 'function_name');

function function_name()
{
    //do stuff
}

Filter Hooks

Filter hooks are used to modify the data. So we can pass the data to our custom filter, modify it and then return the modified data.

To apply a filter,

$message = apply_filter('message' , $message)

And then we can attach our custome function to filter the message

add_filter('message' , 'filter_message');

function filter_message( $message )
{
    return $message . "modified";
}

The filter hooks will always get some data sent to them and will have to return some data. The actions may or may not get data and only need to do some tasks.

Comments

Leave a Reply

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