Welcome to FindNerd.
Today we are going to discuss the hooks in WordPress. We all know hooks are also known as actions and filters. Many of the developers are confused with these terms. They are using filters and actions in their projects but they did not have any clear idea of it so we are here to clarify the hooks. First of all, i want to mention that both are doing the same things with a little difference. Action means additional task which should be taken to reach the goal and filter means to correct the things. In WordPress, we use filters to filter the data such as when we save the post we can make the changes in data before saving or displaying it on front-end. I will explain you the things one by one.
First, we take action. Write the code of your addition task in a function and then we can use inbuilt action or can register a new action to call these function. The action is simply a trigger for our functions. We take an example which will explain the action hook.
function email_task($post_ID) {
$email_id = 'deepakverma.3008@gmail.com';
$subject = "Our Findnerd";
$message = "Check the blogs on Findnerd";
mail($friends, $email_id, $subject, $message);
return $post_ID;
}
add_action('publish_post','email_task');
publish_post hook is inbuilt action. It will trigger a function whenever a post is published. In above example, we are sending emails whenever a post is published. There are lots of actions available in word-press such as save_post, delete_post, deleted user.
Actions |
Properties |
save_post |
It will trigger a function whenever post is edited or created |
delete_post |
It will trigger a function whenever post is deleted |
deleted_user |
Action after user deletion |
send_headers |
Adds additional to current going response
|
There are much more in-built actions are available. You can also build your own action and call it using do_action function. Please have a look.
function my_task(){
//write the code here
}
add_action('my_way','my_task');
do_action('my_way');
You can see in the above example we registered a new action and called it using do_action function.
Now we explain the filter hook. In word-press filters are generally used to modify the data. You can make the changes in data before saving these data in a database using filters. We set the filters between front-end and database to perform the action. you can register the filter using function add_filter. Please have a look.
function filter_base( $content ) {
$detect = array('abuses','disease','...');
$content = str_ireplace( $detect, '{censored}', $content );
return $content;
}
add_filter( 'comment_text', 'filter_base' );
In above example, we are using a comment_text filter to replace the unwanted in the comments. We can also create our own filters and call it using an apply_filter function.
function custom_filter_callback()
{
//write you action here
}
add_filter('custom_filter','custom_filter_callback');
apply_filter('custom_filter');
0 Comment(s)