How to Trigger a Filter in WordPress

The function apply_filters triggers a filter in WordPress.

Background

WordPress filters are a mechanism to allow the replacement of values produced by the code being run. A filter consists of a name and a set of callbacks.

Triggering a filter means executing all callbacks hooked to the filter. The execution is sequential according to the priority of each callback.

Syntax

apply_filters($tag, $value, $var1, …) executes all callbacks hooked to the $tag filter and returns a filtered version of $value. Parameters after $value, if any, are to provide context.

Each callback receives the result produced by the previous one, or $value if it is the first callback, and returns an output. The result is the output of the last callback in the queue. If no callbacks were hooked to the filter, the result is equal to $value.

WordPress also has the function apply_filters_ref_array($tag, $args) to trigger filters. The difference is that in this case arguments are supplied as elements of the $args array.

A call to apply_filters or apply_filters_ref_array creates an extension point. Anyone can hook functions to the filter to inject custom code that replaces the data being filtered.

Examples

The WordPress Core triggers filters extensively. To check it, open the search feature of the IDE and find occurrences of apply_filters or apply_filters_ref_array in the codebase.

For example, the 'wp_revisions_to_keep' filter is triggered in the file revisions.php to allow replacing the number of revisions that WordPress keeps for a post

/**
 * Filters the number of revisions to save for the given post.
 *
 * Overrides the value of WP_POST_REVISIONS.
 *
 * @since 3.6.0
 *
 * @param int     $num  Number of revisions to store.
 * @param WP_Post $post Post object.
 */
return (int) apply_filters( 'wp_revisions_to_keep', $num, $post );

and the 'post_link' filter is triggered in the file link-template.php to allow specifying a new permalink for a post.

/**
 * Filters the permalink for a post.
 *
 * Only applies to posts with post_type of 'post'.
 *
 * @since 1.5.0
 *
 * @param string  $permalink The post's permalink.
 * @param WP_Post $post      The post in question.
 * @param bool    $leavename Whether to keep the post name.
 */
return apply_filters( 'post_link', $permalink, $post, $leavename );

Further reading

I recommend the other tutorials in this series to learn more about filters in WordPress.

Exercise

Suppose a solution where posts can be locked or unlocked. Develop a function that returns the lock status of a post. The function should allow plugins and themes to customize the output.

Source code

The source code developed in this tutorial, including a possible answer to the exercise, is available here.

Open chat
Need help?
Hi! 🤝 Open the chat if you have any question, feedback, or business proposal. I would love to hear from you.