Skip to content

Instantly share code, notes, and snippets.

@jekkilekki
Created October 16, 2016 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jekkilekki/bad101701d738d742793a2d7ef81a8f8 to your computer and use it in GitHub Desktop.
Save jekkilekki/bad101701d738d742793a2d7ef81a8f8 to your computer and use it in GitHub Desktop.
Create custom Action and Filter hooks for your plugins in WordPress
<?php
/**
* Learn how to create custom Action and Filter hooks.
*
* @link https://www.lynda.com/PHP-tutorials/Creating-custom-hooks/508212/547129-4.html
*/
/**
* 1. Custom FILTER Hook ------------------------------
*/
function list_all_items() {
$items = array(
'item 1',
'item 2',
'item 3',
);
$list = '<ul>';
// If we have a custom filter hook, then call it here
if ( has_filter( 'add_more_items' ) ) {
$items = apply_filters( 'add_more_items', $items );
}
foreach ( $items as $item ) {
$list .= '<li>' . $item . '</li>';
}
$list .= '</ul>';
return $list;
}
// Custom Filter hook
add_filter( 'add_more_items', 'specify_filter_action' );
function specify_filter_action( $items ) {
$items[] = 'item 4';
return $items;
}
/**
* 2. Custom ACTION Hook ------------------------------
*/
// 1. Define the action hook
function my_custom_action() {
do_action( 'my_custom_action', 1 );
}
// 2. Attach a function to the hook
add_action( 'my_custom_action', 'specify_action' );
function specify_action() {
echo 'Do something here.';
}
// 3. Call the action hook
my_custom_action();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment