Using WordPress ‘apply_filters()’ PHP function

The apply_filters() WordPress PHP function invokes all functions that have been linked to a specific filter hook. You can create new filter hooks by calling this function and specifying the new hook’s name using the $hook_name parameter. This function also lets you pass multiple additional arguments to the hooks.

Usage

Here’s a basic example of how to use the function:

// Define the filter callback function.
function example_callback( $string, $arg1, $arg2 ) {
    // (maybe) modify $string.
    return $string;
}

// Attach the 'example_callback' function to 'example_filter'.
add_filter( 'example_filter', 'example_callback', 10, 3 );

// Apply the filters by calling 'apply_filters'.
$value = apply_filters( 'example_filter', 'filter me', $arg1, $arg2 );

In this example, ‘example_filter’ is the filter hook, ‘filter me’ is the value being filtered, and $arg1 and $arg2 are additional arguments passed to the callback.

Parameters

  • $hook_name (string): The name of the filter hook.
  • $value (mixed): The value to filter.
  • $args (mixed): Additional parameters to pass to the callback functions.

More information

See WordPress Developer Resources: apply_filters

Note: The apply_filters function doesn’t create filter hooks. If add_filter( ‘filter_name’, ‘filter_function’ ) isn’t executed in the code, using apply_filters( ‘filter_name’, $value ) will return the value of $value by default.

Examples

Echo after Filtering

echo apply_filters( $tag, $value );

This code applies the filters to $value and then echoes the result.

Get Filtered

$myvar = apply_filters( $tag, $value );

This code applies the filters to $value and then assigns the result to $myvar.

Additional Filter Arguments

$myvar = apply_filters( $tag, $value, $param, $otherparam );

This code applies the filters to $value, with $param and $otherparam as additional arguments, and then assigns the result to $myvar.

Custom Title Filter

$my_custom_title = apply_filters('the_title', ' My Custom Title (tm) ');

This code applies the ‘the_title’ filter to ‘ My Custom Title ™ ‘, and then assigns the result to $my_custom_title.

Specifying Number of Arguments

add_filter( 'example_filter', 'example_callback', 10, 3 );

This code attaches ‘example_callback’ to ‘example_filter’, with 10 as the priority and 3 as the accepted arguments. This prevents errors like “Missing argument 2 for example_callback()”.