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

What's hot

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

What's hot (20)

Optimizing Magento by Preloading Data
Optimizing Magento by Preloading DataOptimizing Magento by Preloading Data
Optimizing Magento by Preloading Data
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with Rspec
 
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark BrocatoSenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
What's new for developers in Dynamics 365 v9: Client API enhancement
What's new for developers in Dynamics 365 v9: Client API enhancementWhat's new for developers in Dynamics 365 v9: Client API enhancement
What's new for developers in Dynamics 365 v9: Client API enhancement
 
Smarter Interfaces with jQuery (and Drupal)
Smarter Interfaces with jQuery (and Drupal)Smarter Interfaces with jQuery (and Drupal)
Smarter Interfaces with jQuery (and Drupal)
 
Fixing Magento Core for Better Performance - Ivan Chepurnyi
Fixing Magento Core for Better Performance - Ivan ChepurnyiFixing Magento Core for Better Performance - Ivan Chepurnyi
Fixing Magento Core for Better Performance - Ivan Chepurnyi
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Best Practices for Magento Debugging
Best Practices for Magento Debugging Best Practices for Magento Debugging
Best Practices for Magento Debugging
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin developmentZarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful Code
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Angular 2.0 - What to expect
Angular 2.0 - What to expectAngular 2.0 - What to expect
Angular 2.0 - What to expect
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandler
 

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

Plug in development
Plug in developmentPlug in development
Plug in development
Lucky Ali
 
WordPress plugin #2
WordPress plugin #2WordPress plugin #2
WordPress plugin #2
giwoolee
 
Best practices in WordPress Development
Best practices in WordPress DevelopmentBest practices in WordPress Development
Best practices in WordPress Development
Mindfire Solutions
 
WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practices
markparolisi
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919
Paul Bearne
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
Mostafa Soufi
 
My first WordPress Plugin
My first WordPress PluginMy first WordPress Plugin
My first WordPress Plugin
Abbas Siddiqi
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
arcware
 
Empowering users: modifying the admin experience
Empowering users: modifying the admin experienceEmpowering users: modifying the admin experience
Empowering users: modifying the admin experience
Beth Soderberg
 
Getting to The Loop - London Wordpress Meetup July 28th
Getting to The Loop - London Wordpress Meetup  July 28thGetting to The Loop - London Wordpress Meetup  July 28th
Getting to The Loop - London Wordpress Meetup July 28th
Chris Adams
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress plugin
Anthony Montalbano
 
WordPress Hooks Action & Filters
WordPress Hooks Action & FiltersWordPress Hooks Action & Filters
WordPress Hooks Action & Filters
Nirav Mehta
 
WordPress Plugin Basics
WordPress Plugin BasicsWordPress Plugin Basics
WordPress Plugin Basics
Amanda Giles
 
WordPress Queries - the right way
WordPress Queries - the right wayWordPress Queries - the right way
WordPress Queries - the right way
Anthony Hortin
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
WordPress basic fundamental of plugin development and creating shortcode
WordPress basic fundamental of plugin development and creating shortcodeWordPress basic fundamental of plugin development and creating shortcode
WordPress basic fundamental of plugin development and creating shortcode
Rakesh Kushwaha
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
WordCamp Sydney
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
Tammy Hart
 
Moodle Quick Forms
Moodle Quick FormsMoodle Quick Forms
Moodle Quick Forms
Jalpa Bhavsar
 
How To Write a WordPress Plugin
How To Write a WordPress PluginHow To Write a WordPress Plugin
How To Write a WordPress Plugin
Andy Stratton
 

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

Plug in development
Plug in developmentPlug in development
Plug in development
 
WordPress plugin #2
WordPress plugin #2WordPress plugin #2
WordPress plugin #2
 
Best practices in WordPress Development
Best practices in WordPress DevelopmentBest practices in WordPress Development
Best practices in WordPress Development
 
WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practices
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
 
My first WordPress Plugin
My first WordPress PluginMy first WordPress Plugin
My first WordPress Plugin
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
Empowering users: modifying the admin experience
Empowering users: modifying the admin experienceEmpowering users: modifying the admin experience
Empowering users: modifying the admin experience
 
Getting to The Loop - London Wordpress Meetup July 28th
Getting to The Loop - London Wordpress Meetup  July 28thGetting to The Loop - London Wordpress Meetup  July 28th
Getting to The Loop - London Wordpress Meetup July 28th
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress plugin
 
WordPress Hooks Action & Filters
WordPress Hooks Action & FiltersWordPress Hooks Action & Filters
WordPress Hooks Action & Filters
 
WordPress Plugin Basics
WordPress Plugin BasicsWordPress Plugin Basics
WordPress Plugin Basics
 
WordPress Queries - the right way
WordPress Queries - the right wayWordPress Queries - the right way
WordPress Queries - the right way
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
WordPress basic fundamental of plugin development and creating shortcode
WordPress basic fundamental of plugin development and creating shortcodeWordPress basic fundamental of plugin development and creating shortcode
WordPress basic fundamental of plugin development and creating shortcode
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
 
Moodle Quick Forms
Moodle Quick FormsMoodle Quick Forms
Moodle Quick Forms
 
How To Write a WordPress Plugin
How To Write a WordPress PluginHow To Write a WordPress Plugin
How To Write a WordPress Plugin
 

Recently uploaded

Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
aymanquadri279
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 

Recently uploaded (20)

Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 

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