Tutorial

How to Unhook a Function From a Filter in WordPress

The function remove_filter unhooks a function from 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.

In some cases, a function hooked to a filter causes an undesired result when the filter is triggered. In other cases, the hooking is unnecessary.

Syntax

remove_filter($tag, $function, $priority) removes the function $function from the set of callbacks of the $tag filter. $priority is the current priority of $function within the set of callbacks. If $priority is not specified, it takes a value of 10. The result is TRUE if the function was successfully removed, otherwise FALSE.

Keep in mind these tips to avoid common errors:

  • $priority must match the priority specified in the add_filter call that hooked the function to the filter
  • remove_filter must be executed after the corresponding add_filter call

Example

By default, WordPress replaces double line breaks in the post content with <p> elements. It happens because the WordPress Core hooks the function wpautop to the 'the_content' filter.

Follow this procedure to disable the previous behavior. It is adaptable to any filter/function pair.

Step 1: Find where the function is hooked to the filter in the codebase.

The function add_filter hooks a function to a filter in WordPress. Open the search feature of the IDE and find occurrences of the text 'wpautop' in the codebase. Go to the occurrence where the text appears in a call to add_filter and 'the_content' is the target filter. You will find that this occurrence is in the file default-filters.php.

Do not forget the single quotes in the search criterion.

add_filter('the_content', 'wpautop');

Step 2: Unhook the function from the filter.

Copy the previous statement to a location executed later. Replace add_filter with remove_filter.

remove_filter('the_content', 'wpautop');

Step 3: Test.

Visit a post containing double line breaks in the post content and verify that they were not converted to <p> elements. Note that this conversion never happens if you are using the block editor.

Further reading

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

Exercise

By default, if the post content or the post excerpt contains smiley codes, WordPress renders the corresponding image. Propose a solution to disable this behavior.

/* Sample smiley codes */
:) 
:D 
:( 
;) 
:|

Source code

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

WordPress

Related Tutorials