How Filter Works In WordPress

Filters In WordPress

Filter Hooks are very powerful features of wordpress that provide huge amount of flexibility for modifying wordpress, including custom themes and plugins. In this tutorial, I'm just showing a simple example that demonstrates what a filter hook does.

There are four core functions that use when working with filters:

  • add_filter(): Used for adding new custom filter.
  • remove_filter(): used for removing an already registered filter.
  • apply_filters(): runs the provided data through the specified filter.
  • has_filter(): checks whether a specific filter has been registered or not.

You can think of a filter as a method for modifying data. Here an example for following colors:

function demo_show_colors() {    
    $colors = array('Red', 'Green', 'Blue');
    $list = '<ul>';
    foreach($colors as $color) {
   	 $list .= '<li>' . $color . '</li>';
    }
    $list .= '</ul>';
    return $list;    
}
echo demo_show_colors();

Output:

* Red

* Green

* Blue

Now if we want to modify list of colors via plugin, we need to include a filter.

function demo_show_colors() {
    $colors = array('Red', 'Green', 'Blue');
    $list = '<ul>';
    if(has_filter('modify_colors')){
   	 $colors = apply_filters('modify_colors', $colors);
    }
    foreach($colors as $color) {
   	 $list .= '<li>' . $color . '</li>';
    }
    $list .= '</ul>';
    return $list;    
}

In if condition we check if there "modify_colors" filter exists then apply that filter to $color array.

After applying filter we can add colors, remove selective colors, change color name etc.

Here's Example For Add Color:

function add_extra_color($colors) 
{
    $extra_color = array('Navy', 'Skyblue', 'Brown');
    $colors = array_merge($extra_color, $colors);
    return $colors;
}
add_filter('modify_colors', 'add_extra_color');

Output:

* Red

* Green

* Blue

* Navy

* Skyblue

* Brown

remove_filter is used for just remove addition done by the add_filter() if any.

Here is example of remove filter:

function add_extra_color($colors) 
{
	$extra_color = array('Navy','Skyblue','Brown');
	$colors = array_merge($extra_color, $colors);
	return $colors;
}
add_filter('modify_colors', 'add_extra_color')

function demo_show_colors() 
{
	$colors = array('Red','Green','Blue');
	$list = '<ul>';
	if(has_filter('modify_colors')){
    	$colors = apply_filters('modify_colors', $colors);
	}
	foreach($colors as $color) {
    	$list .= '<li>' . $color . '</li>';
	}
	$list .= '</ul>';
	return $list;    
}

remove_filter('modify_colors','add_extra_color');

Output:

* Red

* Green

* Blue

Hope you all understood the concept of Filters in Wordpress. Feel free to contact us for any suggestions/queries and hire wordpress developer. I am a feedback lover!