How to create custom action hook in wordpress?

Action hook is triggered while an event occurs like publishing post,changing themes,plugin activation etc. To create/register custom action hook you need to use add_action() function.

Signature of this function


add_action('action_hook_name','function_to_call');

Why we need Action hook

WordPress provides feature of hooks to extend its functionality without affecting the core modules.If WordPress hooks doesn’t exist and we want to add some functioanlity after add/update a new post then we need to change some core modules and when new wordpress release comes all the changes made by us will be lost or we need not to upgrade the wordpress.

Create/Register your own action hook

Here is an example custom hook to save records to a user defined table.You can add the code below to functions.php or can be in a plugin file.


<?php

//Here we are registering an action hook

add_action('save_products','doSave');

function doSave($data){

global $wpdb;

$product['name']=$data['product_title'];

$product['price'] =$data['price'];

$wpdb->insert('product',$product);

//Define the code whatever you need with an action

}

?>

//To call/invoke an action hook you need to use <strong>do_action()</strong> function.

//Signature of function

do_action('action_name','parameters');

//In our case do_action will have following arguments

do_action('save_products',$_REQUEST)

There are some following pre-defined action hooks are:-

1. wp_head
2. wp_footer
3. save_post

Leave a Reply