Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.