Check a WordPress Filter in a Conditional Statement

WordPress’s system of actions and filters are a large part of what makes it such a great platform for developers. It allows us to expand and modify behavior without changing the core code.

Recently I wanted to enable a feature unless a filter had been added. It serves essentially the same functionality as saving and checking an option but without having to touch the database.

Here’s how you do it. First you create a conditional statement in PHP. We’re setting the default value to false so that this statement will evaluate as true and the code inside it will run.

if ( false === apply_filters( 'custom_filter', false ) ) {

What this does is the code inside the conditional statement will execute unless there is an active filter called custom_filter that returns true. Something like this:

add_filter( 'custom_filter', '__return_true' );

Now when this exists, the code inside the conditional won’t be executed because custom_filter will return false.

Leave a Reply

%d bloggers like this: