SlideShare a Scribd company logo
Demystifying Hooks,
Actions & Filters
A quick run through by Damien Carbery
Actions and filters are the means to extend WordPress. Without them
WordPress could not be extended and there would not be any plugins.
Look for do_action() and apply_filters() function calls.
They are everywhere
Did you know that WordPress uses actions and filters
internally?
In WordPress 4.9.5 I found 867 do_action() calls and
1743 apply_filters() calls.
Dogfooding
What are they?
They are everywhere but what are they?
âž” Actions - do_action()
Run your code at a certain point. Don't
return any data.
âž” Filters - apply_filters()
Modify data at a certain point. Return
some data.
Actions are like a music festival
The available actions are like the acts at a music festival. If you want to see an act you
must put your name down for it. You may also say what position in the queue you'd
like to be.
When an act is coming on you'll be called. You will be called in the queue position you
specified.
You can use this time to get ready e.g. put on a t-shirt with the band on it. When
you're ready you say so.
add_action( 'band_name', 'my_name', $position );
Core actions - a summary
The Codex Action Reference page list 50 actions that are
run during a typical page request - you might recognise
names like 'plugins_loaded', 'after_setup_theme', 'init',
'pre_get_posts' or 'wp_head'
Tip
"WordPress Action
Reference" is at:
https://codex.wordpres
s.org/Plugin_API/Action
_Reference
Everything in its own time
Actions are all times where code (internal or in a plugin or a
theme) can be run. Plugins and themes can add their own
actions.
For example: Plugins are loaded alphabetically so plugin
"AAA" will have to wait until the 'plugins_loaded' action to
use functions in plugin 'ZZZ'.
do_action( 'action_name' );
WordPress calls functions that have added themselves to
this action with code like:
add_action('action_name','my_function',10);
function my_function() {
echo '<!-- In action_name -->';
}
Tip
The third parameter is
the priority. The default
is 10. You can omit it or
set it to any positive
number.
The 'wp_head' action is used internally and by themes and plugins.
wp_head() is most frequently seen in a theme's header.php. It simply calls:
do_action( 'wp_head' );
In wp-includes/default-filters.php 23 functions are set to run at this point e.g.
add_action( 'wp_head', 'wp_generator' );
This produces the meta tag with the WordPress version:
<meta name="generator" content="WordPress 4.9.5" />
do_action() example
do_action() to add content
You can use a do_action() to run code to inject content, or set up more
add_action() calls or remove some code that is due to run later.
Let's add a meta tag with our name:
add_action('wp_head','my_meta_name');
function my_meta_name() { ?>
<meta name="author" content="Damien Carbery" />
<?php }
do_action() to remove code
Let's remove the "generator" meta tag that was added with:
add_action( 'wp_head', 'wp_generator' );
Note the priority that it is set to run before the code is run.
add_action('wp_head','remove_generator', 9);
function remove_generator() {
remove_action( 'wp_head', 'wp_generator' );
}
do_action() for more add_action()
Maybe move stuff around - we must make the change after it is added but before
it is executed. In WooCommerce lets move the price to be above the product
title.
In the WooCommerce template file that displays a single product it has a number
of do_action() calls. The file includes comments listing the internal
WooCommerce functions attached each action. It also lists the position number
that was used in the add_action() call - you need this for a remove_action() call.
do_action() for more add_action()
do_action( 'woocommerce_before_single_product' );
do_action( 'woocommerce_before_single_product_summary' );
// @hooked woocommerce_template_single_title - 5
// @hooked woocommerce_template_single_price - 10
do_action( 'woocommerce_single_product_summary' );
To move the price above the title I need to run my code before the price and title
functions are run. I am going to run during the
'woocommerce_before_single_product' action.
do_action() for more add_action()
add_action('woocommerce_before_single_product', 'mover' );
function mover() {
remove_action( 'woocommerce_single_product_summary',
'woocommerce_template_single_price', 10 );
add_action( 'woocommerce_single_product_summary',
'woocommerce_template_single_price', 4 );
}
The price position was 10. Title was 5 so we used 4 to display before it.
Filters are like "Pass The Parcel"
When a filter is run it's like passing the parcel (data) around and then back to the start
position.
You can change the parcel (data) if you want - e.g. tear off a layer, or add another
layer or put in a totally new parcel. Whatever you do you must pass a parcel (data)
back.
You can also do other things like get ready for that forthcoming music act.
You may be given extra relevant info when you get the parcel e.g. a boy wrapped it.
add_filter('place_in_game','my_name',$position,$num_args );
add_filter() to add content
'the_content' is a filter that runs when the_content() function is called.
Let's use it to append some copyright info to the page.
add_filter('the_content','append_copyright');
function append_copyright( $content ) {
return $content . '<p>Copyright Me 2018</p>';
}
add_filter() to change content
In WooCommerce let's not show whether a product is in stock. The called
function receives 2 parameters - the html that will be shown and a copy of the
product object - maybe you'll only show info for some products.
add_filter('woocommerce_get_stock_html','noinfo',10,2);
function noinfo( $html, $product ) {
if ( $product->is_on_sale() ) return '';
return $html;
}
add_filter() while debugging
You don't have to change the passed data. You may use the opportunity to look
at other data while debugging.
add_filter('the_content','content_debug');
function content_debug( $content ) {
error_log( 'Content: ' . $content );
error_log( 'URL: ' . $_SERVER['REQUEST_URI'] );
return $content;
}
Where does this code go?
New users are often told to put snippets of code in the theme's functions.php file.
Make sure you are using a child theme otherwise you'll lose the code when the
(parent) theme is updated.
Functional plugin
You could put snippets into a plugin and activate it. Create a file in
wp-content/plugins and give it a header comment like:
<?php
/*
Plugin Name: My Functional Plugin
Plugin URI: https://www.damiencarbery.com
Description: A place for my code snippets.
Author: Damien Carbery
Version: 0.1
*/
Be Fearless!
Don't be intimidated by actions or filters.
âž” Actions
Get in line for the gig
âž” Filters
Pass the parcel
âž” Functional plugin
A safe way to add code.
Damien Carbery
https://www.damiencarbery.com
@DaymoBrew

More Related Content

PPTX
Actions & Filters In WordPress
Konstantin Obenland
 
PDF
Wordpress plugin development from Scratch
Ocaka Alfred
 
PDF
Factory Girl
Gabe Evans
 
KEY
Actions filters
John Dillick
 
PDF
Symfony 4 Workshop - Limenius
Ignacio MartĂ­n
 
PPTX
You don’t know query - WordCamp UK Edinburgh 2012
l3rady
 
PPTX
Using of TDD practices for Magento
Ivan Chepurnyi
 
PPTX
Hooking with WordPress by Rahul Prajapati - COEP FOSSMeet March 2019
rtCamp
 
Actions & Filters In WordPress
Konstantin Obenland
 
Wordpress plugin development from Scratch
Ocaka Alfred
 
Factory Girl
Gabe Evans
 
Actions filters
John Dillick
 
Symfony 4 Workshop - Limenius
Ignacio MartĂ­n
 
You don’t know query - WordCamp UK Edinburgh 2012
l3rady
 
Using of TDD practices for Magento
Ivan Chepurnyi
 
Hooking with WordPress by Rahul Prajapati - COEP FOSSMeet March 2019
rtCamp
 

What's hot (20)

PPTX
Optimizing Magento by Preloading Data
Ivan Chepurnyi
 
PPTX
How to perform debounce in react
BOSC Tech Labs
 
PDF
Manipulating Magento - Meet Magento Netherlands 2018
Joke Puts
 
PPTX
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine
 
PPT
Ruby on Rails testing with Rspec
Bunlong Van
 
PPTX
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
Sencha
 
DOCX
VPN Access Runbook
Taha Shakeel
 
PPTX
What's new for developers in Dynamics 365 v9: Client API enhancement
Kenichiro Nakamura
 
PPT
Smarter Interfaces with jQuery (and Drupal)
aasarava
 
PPTX
Fixing Magento Core for Better Performance - Ivan Chepurnyi
Meet Magento Spain
 
KEY
Unit testing zend framework apps
Michelangelo van Dam
 
PDF
Best Practices for Magento Debugging
varien
 
PDF
購物車程式架構簡介
Jace Ju
 
ODP
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
Zarafa
 
PDF
Rails 3 Beautiful Code
GreggPollack
 
PDF
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
PDF
Angular 2.0 - What to expect
Allan Marques Baptista
 
PDF
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Ivan Chepurnyi
 
PDF
Rails 3 overview
Yehuda Katz
 
ODP
HTML::FormHandler
bbeeley
 
Optimizing Magento by Preloading Data
Ivan Chepurnyi
 
How to perform debounce in react
BOSC Tech Labs
 
Manipulating Magento - Meet Magento Netherlands 2018
Joke Puts
 
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine
 
Ruby on Rails testing with Rspec
Bunlong Van
 
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
Sencha
 
VPN Access Runbook
Taha Shakeel
 
What's new for developers in Dynamics 365 v9: Client API enhancement
Kenichiro Nakamura
 
Smarter Interfaces with jQuery (and Drupal)
aasarava
 
Fixing Magento Core for Better Performance - Ivan Chepurnyi
Meet Magento Spain
 
Unit testing zend framework apps
Michelangelo van Dam
 
Best Practices for Magento Debugging
varien
 
購物車程式架構簡介
Jace Ju
 
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
Zarafa
 
Rails 3 Beautiful Code
GreggPollack
 
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
Angular 2.0 - What to expect
Allan Marques Baptista
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Ivan Chepurnyi
 
Rails 3 overview
Yehuda Katz
 
HTML::FormHandler
bbeeley
 
Ad

Similar to Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018 (20)

PDF
Jumping Into WordPress Plugin Programming
Dougal Campbell
 
PPTX
Let’s write a plugin
Brian Layman
 
PPTX
2016 WordCamp Pittsburgh - Let's Write a Plugin
Brian Layman
 
PPTX
WordPress Hooks Action & Filters
Nirav Mehta
 
PDF
Introduction to WordPress Hooks 2016
Ian Wilson
 
PDF
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
WordCamp Sydney
 
PPTX
Using Actions and Filters in WordPress to Make a Plugin Your Own
Brian Hogg
 
PPT
WordPress Plugins
OpenSource Technologies Pvt. Ltd.
 
PDF
WooCommerce: Filter Hooks
Rodolfo Melogli
 
PDF
Plugin development demystified 2017
ylefebvre
 
PPT
Word press Plugins by WordPress Experts
Yameen Khan
 
PPTX
WordPress plugin #2
giwoolee
 
PDF
How I Became a WordPress Hacker
Mike Zielonka
 
PPTX
Introduction to WordPress Development - Hooks
Edmund Chan
 
PDF
My first WordPress Plugin
Abbas Siddiqi
 
PDF
Hooked on WordPress: WordCamp Columbus
Shawn Hooper
 
ODP
Beginning WordPress Plugin Development
Aizat Faiz
 
KEY
doing_it_right() with WordPress
ryanduff
 
PDF
Introduction to Wordpress Hooks
Anthony Hartnell
 
PDF
Bending word press to your will
Tom Jenkins
 
Jumping Into WordPress Plugin Programming
Dougal Campbell
 
Let’s write a plugin
Brian Layman
 
2016 WordCamp Pittsburgh - Let's Write a Plugin
Brian Layman
 
WordPress Hooks Action & Filters
Nirav Mehta
 
Introduction to WordPress Hooks 2016
Ian Wilson
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
WordCamp Sydney
 
Using Actions and Filters in WordPress to Make a Plugin Your Own
Brian Hogg
 
WooCommerce: Filter Hooks
Rodolfo Melogli
 
Plugin development demystified 2017
ylefebvre
 
Word press Plugins by WordPress Experts
Yameen Khan
 
WordPress plugin #2
giwoolee
 
How I Became a WordPress Hacker
Mike Zielonka
 
Introduction to WordPress Development - Hooks
Edmund Chan
 
My first WordPress Plugin
Abbas Siddiqi
 
Hooked on WordPress: WordCamp Columbus
Shawn Hooper
 
Beginning WordPress Plugin Development
Aizat Faiz
 
doing_it_right() with WordPress
ryanduff
 
Introduction to Wordpress Hooks
Anthony Hartnell
 
Bending word press to your will
Tom Jenkins
 
Ad

Recently uploaded (20)

PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Exploring AI Agents in Process Industries
amoreira6
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Presentation about variables and constant.pptx
kr2589474
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 

Demystifying Hooks, Actions & Filters - WordCamp Belfast 2018

  • 1. Demystifying Hooks, Actions & Filters A quick run through by Damien Carbery
  • 2. Actions and filters are the means to extend WordPress. Without them WordPress could not be extended and there would not be any plugins. Look for do_action() and apply_filters() function calls. They are everywhere
  • 3. Did you know that WordPress uses actions and filters internally? In WordPress 4.9.5 I found 867 do_action() calls and 1743 apply_filters() calls. Dogfooding
  • 4. What are they? They are everywhere but what are they? âž” Actions - do_action() Run your code at a certain point. Don't return any data. âž” Filters - apply_filters() Modify data at a certain point. Return some data.
  • 5. Actions are like a music festival The available actions are like the acts at a music festival. If you want to see an act you must put your name down for it. You may also say what position in the queue you'd like to be. When an act is coming on you'll be called. You will be called in the queue position you specified. You can use this time to get ready e.g. put on a t-shirt with the band on it. When you're ready you say so. add_action( 'band_name', 'my_name', $position );
  • 6. Core actions - a summary The Codex Action Reference page list 50 actions that are run during a typical page request - you might recognise names like 'plugins_loaded', 'after_setup_theme', 'init', 'pre_get_posts' or 'wp_head' Tip "WordPress Action Reference" is at: https://codex.wordpres s.org/Plugin_API/Action _Reference
  • 7. Everything in its own time Actions are all times where code (internal or in a plugin or a theme) can be run. Plugins and themes can add their own actions. For example: Plugins are loaded alphabetically so plugin "AAA" will have to wait until the 'plugins_loaded' action to use functions in plugin 'ZZZ'.
  • 8. do_action( 'action_name' ); WordPress calls functions that have added themselves to this action with code like: add_action('action_name','my_function',10); function my_function() { echo '<!-- In action_name -->'; } Tip The third parameter is the priority. The default is 10. You can omit it or set it to any positive number.
  • 9. The 'wp_head' action is used internally and by themes and plugins. wp_head() is most frequently seen in a theme's header.php. It simply calls: do_action( 'wp_head' ); In wp-includes/default-filters.php 23 functions are set to run at this point e.g. add_action( 'wp_head', 'wp_generator' ); This produces the meta tag with the WordPress version: <meta name="generator" content="WordPress 4.9.5" /> do_action() example
  • 10. do_action() to add content You can use a do_action() to run code to inject content, or set up more add_action() calls or remove some code that is due to run later. Let's add a meta tag with our name: add_action('wp_head','my_meta_name'); function my_meta_name() { ?> <meta name="author" content="Damien Carbery" /> <?php }
  • 11. do_action() to remove code Let's remove the "generator" meta tag that was added with: add_action( 'wp_head', 'wp_generator' ); Note the priority that it is set to run before the code is run. add_action('wp_head','remove_generator', 9); function remove_generator() { remove_action( 'wp_head', 'wp_generator' ); }
  • 12. do_action() for more add_action() Maybe move stuff around - we must make the change after it is added but before it is executed. In WooCommerce lets move the price to be above the product title. In the WooCommerce template file that displays a single product it has a number of do_action() calls. The file includes comments listing the internal WooCommerce functions attached each action. It also lists the position number that was used in the add_action() call - you need this for a remove_action() call.
  • 13. do_action() for more add_action() do_action( 'woocommerce_before_single_product' ); do_action( 'woocommerce_before_single_product_summary' ); // @hooked woocommerce_template_single_title - 5 // @hooked woocommerce_template_single_price - 10 do_action( 'woocommerce_single_product_summary' ); To move the price above the title I need to run my code before the price and title functions are run. I am going to run during the 'woocommerce_before_single_product' action.
  • 14. do_action() for more add_action() add_action('woocommerce_before_single_product', 'mover' ); function mover() { remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 ); add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 4 ); } The price position was 10. Title was 5 so we used 4 to display before it.
  • 15. Filters are like "Pass The Parcel" When a filter is run it's like passing the parcel (data) around and then back to the start position. You can change the parcel (data) if you want - e.g. tear off a layer, or add another layer or put in a totally new parcel. Whatever you do you must pass a parcel (data) back. You can also do other things like get ready for that forthcoming music act. You may be given extra relevant info when you get the parcel e.g. a boy wrapped it. add_filter('place_in_game','my_name',$position,$num_args );
  • 16. add_filter() to add content 'the_content' is a filter that runs when the_content() function is called. Let's use it to append some copyright info to the page. add_filter('the_content','append_copyright'); function append_copyright( $content ) { return $content . '<p>Copyright Me 2018</p>'; }
  • 17. add_filter() to change content In WooCommerce let's not show whether a product is in stock. The called function receives 2 parameters - the html that will be shown and a copy of the product object - maybe you'll only show info for some products. add_filter('woocommerce_get_stock_html','noinfo',10,2); function noinfo( $html, $product ) { if ( $product->is_on_sale() ) return ''; return $html; }
  • 18. add_filter() while debugging You don't have to change the passed data. You may use the opportunity to look at other data while debugging. add_filter('the_content','content_debug'); function content_debug( $content ) { error_log( 'Content: ' . $content ); error_log( 'URL: ' . $_SERVER['REQUEST_URI'] ); return $content; }
  • 19. Where does this code go? New users are often told to put snippets of code in the theme's functions.php file. Make sure you are using a child theme otherwise you'll lose the code when the (parent) theme is updated.
  • 20. Functional plugin You could put snippets into a plugin and activate it. Create a file in wp-content/plugins and give it a header comment like: <?php /* Plugin Name: My Functional Plugin Plugin URI: https://www.damiencarbery.com Description: A place for my code snippets. Author: Damien Carbery Version: 0.1 */
  • 21. Be Fearless! Don't be intimidated by actions or filters. âž” Actions Get in line for the gig âž” Filters Pass the parcel âž” Functional plugin A safe way to add code. Damien Carbery https://www.damiencarbery.com @DaymoBrew