There are many reasons why WordPress has become so popular as a Content Management System (CMS) in the last couple of years.
WordPress powered 26.9% of the entire internet in 2016 and its market share among all free content management system is close to 60%. Not just because it is open-source but it’s also the easiest CMS to integrate with almost all of your needs. One of the reasons from the developer’s point of view is because WordPress is very easy to modify by using action, filter, and hook. With this function, we don’t need to change any of WordPress’s core files.
The Basics
To display a single frontend page WordPress has to do a lot of processes in the background. WordPress allows you to modify those processes using ‘hooks’. There are two types of WordPress hooks:
- Action: WordPress actions let you append your own functionality at a specific process
- Filter: WordPress filters allow you to change and modify data as it is processed
The Analogy
I will not blame you if you still don’t understand what it is all about. Lets use an example: Sam is making a burger, and he offers to add/modify the layers as you wish.
The Breakdown
As we can see do_action function lets you put anything between the layers, and apply filter lets you change what the layer is. Now, lets use the burger analogy with the code:
WordPress Hook: Action
I want to add pickles before lettuce
add_action('before_vegetable', 'my_custom_layer_before_vegetable'); function my_custom_layer_before_vegetable(){ echo 'I am the pickles layer'; }
I want to add pickles and coriander before lettuce
add_action('before_vegetable', 'pickles_layer_before_vegetable', 1); function pickles_layer_before_vegetable(){ echo 'I am the pickles layer'; } add_action('before_vegetable', 'coriander_layer_before_vegetable', 2); function coriander_layer_before_vegetable(){ echo 'I am the coriander layer'; }
Notes: the number 1 & 2 stand for priority, if you wanted coriander to appear above pickles then you just need to switch the priority.
WordPress Hook: Filter
I don’t want lettuce on my burger, please use pickles instead
add_filter('vegetable_filter', 'change_vegetable_filter' ); function change_vegetable_filter( $default ){ return 'I am the pickles layer'; }
I want a crispy patty
add_filter('patty_filter', 'make_it_crispy'); function make_it_crispy( $meat ){ $cooked = deep_fry_task( $meat ); return $cooked; }
Why Use Hooks
Many of WordPress’s core code uses actions and filters, so this is the best practice to modify your code without touching core files. Many plugin and theme developers use this technique to keep code clean and easy to understand.