18.215.189.168 nuevecubica | WordPress Action and Filter Hooks
background
back

Wordpress

WordPress Action and Filter Hooks

Hooks are a way to interact or modify with WordPress code at the specific pre-design spot. learn more.

By Alex Vaught - 01 March 2020

Tags:

Hooks are a way to interact or modify with WordPress code at the specific pre-design spot. There are two kinds of hooks Actions and Filters. To use them, you have to create a Callback and then register it with WordPress Hook.

Actions allow you to add data or change how WordPress operates. Callback functions for Actions will run at a specific point in the execution of WordPress.

And can perform a task, like echoing output to the user or inserting it into the database. Actions do not return anything to the calling Hook.

 

 // callback example Action Hook Function action_hook_sendEmail(){ wp_mail('tester@mail.com','Subject','Message…'); } add_action('init','action_hook_sendEmail'); 

// reference
https://codex.wordpress.org/Plugin_API/Action_Reference

Filters will give you the ability to change data during the execution of WordPress.

Callback functions for Filters will accept a variable, modify it, and return it. They are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. Filters expect to have something returned to them.

 

 // callback example Filter Hook Function filter_hook_content ($content){ $content = $content  . “<p> the end of the content….</p> ”; return $content; } add_filter('the_content','filter_hook_content'); 

// reference
https://codex.wordpress.org/Plugin_API/Filter_Reference

 

WordPress provides many Hooks that you can use, but you can also create your own so that other developers can extend and modify your plugin or theme.

 

Actions vs. Filters 

 

The main difference between an Action and a Filter can be explained as follows:

  • An Action takes the info it receives, does something with it, and returns nothing. In other words: it acts on something and then exits, returning nothing back to the calling Hook.
  • A Filter takes the info it receives, modifies it somehow, and returns it. In other words: it filters something and passes it back to the Hook for further use.

 

In other words:

 

  • An Action interrupts the code flow to do something and then returns back to the normal flow without modifying anything.
  • A Filter is used to modify something in a specific way so that the modification is then used by code later on.