Welcome to FindNerd.
Today I am going to discuss two widely used functions in word-press that are add_action and add_filter. I have described the hooks and its uses in previous blogs so please follow these blogs for the same. Here we are discussing these functions uses and properties. We start with add_action
First of all, you need to write the function as per your requirements and then add_action will help you to call this function on different events.
add_action takes three main arguments.
Arguments |
Properties |
Tag(string) |
It is a required argument and you can pass in-build actions/hooks of wp or can build your own. |
Callback method |
This is also required one. You can pass the function name to call on mention event. |
Priority(int) |
This is an optional one. Sometimes we need to call the different functions for the same event then you can set the priority for these functions to call. the lowest number means the priority is high and If you set the same priority for more than one then they will be fired as in order in which are coded. The default priority is set to 10. |
Accepted args |
It is an optional one. You can mention the number of arguments for the callback function. The default value is set to one argument. |
In above table, we have mentioned the properties of all available arguments of add_action function. let's take a small example.
function post_change_callback($post_id,$post,$update)
{
// write the code here
}
function comment_change_callback($post_id,$post)
{
//write the code here
}
You can put the above code in functions.php or in your plugin files to execute. In above we have created two actions for same event and set the priority for both of them. In same way we can use the function add_filter. It takes the same argument as above mention. Please have a look.
add_action('the_content','content_change_callback',2,1);
function content_change_callback($content)
{
//write the code here
}
In above code we have created a action for the_content and set the priority for the same. I want to mention one other thing here. If you check the source code of add_action function then you will know that word-press developer calling add_filter function inside this function. It means we can call the add_filter function directly instead of add_action. Please have look.
function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
return add_filter($tag, $function_to_add, $priority, $accepted_args);
}
0 Comment(s)