Created
October 16, 2016 06:38
-
-
Save jekkilekki/bad101701d738d742793a2d7ef81a8f8 to your computer and use it in GitHub Desktop.
Create custom Action and Filter hooks for your plugins in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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