How to create hooks and filters in WordPress. Code examples open

How to create hooks and filters in WordPress. Code examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

WordPress hooks are functions that allow you to manipulate a procedure without changing a file in WordPress core. A hook can be applied to both an event (action hook) and a filter (filter hook).

Hooks are essential for any WP user. With their help, you can create new functions or edit the default settings of themes and plugins.

Let’s create our first hook

For example, go to the file header.php our WordPress theme. Open the file and add a new hook:

<?php 
do_action('my_first_hook')
?>

This code calls the my_first_hook action. Actions (hooks) in PHP allow you to execute specific code at specific times within your program. In this case, the code do_action(‘my_first_hook’) tells PHP to execute all the functions that were bound to the my_first_hook hook.

To do this, go to yours function.php, and add:

 
<?php
//Our usual function is to display text
function mycustom() {
    echo 'This text add by hook';
}
//add_action attaches this function to the hook we created
add_action('my_first_hook', 'mycustom');
?>

We will add more text to our hook:

And now we will change the text in places, for this purpose we will use priority of hooks, it is set by 3 parameters:

Pass the variables $ var, $ var2 to our hook

<?php 
do_action('my_first_hook', $var, $var2)
?>

<?php 
function mycustom2($var, $var2) {
    echo $var . $var2;
}
add_action('my_first_hook', 'mycustom2', 1,2);
?>

Сreate a filter

Now let’s talk about the filter, its functionality is very similar to the hook, but created to change values:

<?php 
$color = 'red';
$color = apply_filters('my_first_filter', $color);
?>

in functions.php we will add

<?php 
function myfilter($name) {
    $color = 'black';
    return $color;
}
add_filter('my_first_filter', 'myfilter');
?>

The values that will pass through this filter will change to = ‘black’

Remove hooks and filters?

Sometimes a hook or filter may not be created by you. If it interferes with you by disrupting your theme or plugin, you can easily turn it off using the functions remove_filter and remove_hook

remove_hook

<?php
remove_hook('my_first_hook', 'mycustom');
?>

This code removes the mycustom function, which was bound to the my_first_hook hook.

remove filter

<?php 
remove_filter('mycustom2', 'myfilter');
?>

This code removes the myfilter filter that was bound to the mycustom2 hook. The remove_filter() function is used to remove bound filters from a specific hook in PHP.

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation