How to Use wordpress hooks in wordpress

Hooks Allow us to manipulate data in an easy and safe way.

Two types of hooks.

1.Action Hooks:

Trigger by an event. Allow us to add our on functions to them when every we want. Used for Stuff like “when X Happens, do y”.

2.Filter Hooks:

allow us to Manipulate data. As in “take this X var,do Something in with it(“filter it”) and Return the result”.

Action Hook:

Action Hooks:trigger by an event. Allow us to add our on functions to them when every we want.Used for stuff like “when X happen,do Y”.

do_action("hook_name") //will create our hook
add_action("hook_name","Callback_function", Priority)
 
function callback_function(){
echo "Welcome to Wpdadd"
//code goes here
}

To append text to “welcome to wpdadd” We can create

add_action("hook_name","override_Callback_function", Priority)
 
function callback_function(){
echo "Bye  Wpdadd";
//code goes here
}

If we want to remove the filter we can use.

remove_action( string $tag, callable $function_to_remove, int $priority = 10 )
 
remove_action( 'hook_name', "callback_function", int $priority = 10 )

Filters

Filter Hooks:allow us to Manipulate data.As in “take this X var,do something in with it(‘filter it”) and return the results.

apply_filters($tag,$value,$var ...);
 
add_filter($tag,$function_to_add,$priority,$accepted_args);
 
function function_to_add($arg){
 
  return $arg;
}

Suppose we need to override the hooks we can use.

apply_filter('filter_name', "callback_function",$arg);
 
add_filter($tag,$function_to_add,$priority,$accepted_args);
 
function function_to_add($arg){
 
return  apply_filter('filter_name', "callback_function",$arg);
}
 
 
 
add_filter('filer_name' ,'callback_function');
 
 
function callback_function($arg){
 
 
$arg ="changed";
 
return $arg;
 
}

Suppose we need to Remove the Filters

 remove_filter( $tag, $function_to_remove, $priority );
 
remove_filter( 'hook_name', "callback_function", int $priority = 10 )

Add a Comment

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

9 + 5 =