Hooking with
WordPress
What is Hooking?
Example:
Example:
Methods
- Source Modification
- Modify behavior before the application starts.
- i.e, patch created by reverse engineering the
application
- Runtime Modification
- Modify behavior while the application is running.
Core php example
Hooks
<?php
function do_action( $function_name, $args ) {
if ( function_exists( $function_name ) {
call_user_func( $function_name,
$args );
}
}
?>
<?php
function apply_filter( $function_name, $args ) {
if ( function_exists( $function_name ) {
return call_user_func( $function_name, $args );
}
return $args;
}
?>
WordPress CMS
WordPress Hooks
- Actions
- Execute extra code in between code execution.
- Filters
- Change/Update behaviour of existing code.
WP Action
<?php
do_action( ‘init’);
<?php
function wporg_custom() {
// do something
}
add_action('init', 'wporg_custom');
add_action ( 'hook_name', 'your_function_name', [priority], [accepted_args] );
Examples:
WP Filters
<?php
$title = apply_filter( ‘the_title’, $title );
<?php
function wporg_filter_title($title) {
return 'The ' . $title . ' was filtered';
}
add_filter('the_title', 'wporg_filter_title');
add_filter ( 'hook_name', 'your_filter', [priority], [accepted_args] );
Examples:
Hooking: https://en.wikipedia.org/wiki/Hooking
WP Hooks: https://developer.wordpress.org/plugins/hooks/
WP Actions: https://developer.wordpress.org/plugins/hooks/actions/
WP Filter: https://developer.wordpress.org/plugins/hooks/filters/
References
WP Reference Code
https://core.trac.wordpress.org/browser/trunk/src/wp-
includes/plugin.php#L428
https://core.trac.wordpress.org/browser/trunk/src/wp-
includes/class-wp-hook.php
Got Questions?
Rahul Prajapati
@rahulsprajapati
rahul.prajapati@live.in

Hooking with WordPress by Rahul Prajapati - COEP FOSSMeet March 2019

Editor's Notes

  • #10 Ref: https://docs.google.com/presentation/d/1XGJohCttZnp_4JfQYRJDEvm8axUSAZP3Uok6z_Ubb_E/edit#slide=id.g18fb825758_1_12