Site icon Dhanendran's Blog

How to create custom filter in WordPress?

 

Basically WordPress hooks are categorized into two types;

  1. Action hooks
  2. Filter hooks

Action hooks: As name says, these hooks are called when an action is performed. Action hooks allow you to execute your custom functions which are referred to as actions.

Action hooks allow you to add additional code to the WordPress core or theme so that you can achieve some new functionality or customizations.

Filter hooks: Filters are useful when we want to alter or manipulate the data before or after it’s execution.

Custom Filters:

Let’s dive into creating the custom filters now.

There are two main API’s available in WordPress for creating custom filters.

  1. add_filter()
  2. apply_filters()

add_filter()

add_filter() function is useful when adding new functionality / function to the filters.

add_filter( string $filter_name, callable $function_name, int $priority = 10, int $accepted_args = 1 );

In the add_filter function, we will pass 4 parameters. Filter name (required) will be the name of the filter which we are going to create. Callback function (required) would be the place where we modify or manipulate the data. Priority (optional) is to specify the order in which the functions should get executed and by default it is 10. Accepted args (optional) are the number of arguments that the callback function should accept and bydefault it is 1.

Now, time to create filter.

apply_filters( string $filter_name, mixed $value );

This is it. Now you have created your filter. apply_filters() is the function which will invoke or call all the filters added to it based on the priority set on the filters. Also it sends the argument to the callback functions.  apply_filters() will return the latest modified or manipulated data, which we can use it for further execution.

Let’s see an example.

// defining our filter callback function
function sample_callback( $array, $arg1, $arg2 ) {
    // you can do your data manipulation or modification here
    return $array;
}
add_filter( 'sample_filter', 'sample_callback', 10, 3 );

/*
 * Apply the filters by calling the 'sample_callback' function that we
 * hooked to 'sample_filter' using the add_filter() function above.
 */
$data = apply_filters( 'sample_filter', array('filter me'), $arg1, $arg2 );

In this example, sample_callback function will accept 3 parameters and it’s priority is 10 as default. sample_callback function is attached to sample_filter and it is called by apply_filters() function with 3 arguments.

Hope we are done with the custom filters. Thanks… 🙂

Exit mobile version