• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Programming / WordPress Filter Early Return Pattern

WordPress Filter Early Return Pattern

Last updated on August 31, 2021 by Sal Ferrarello

A common programming pattern when using WordPress filters is the early return pattern (also know as the “short-circuit” pattern). This pattern is useful when you want to allow a filter to override a value that is “expensive” to calculate.

Original Code

Imagine we have some PHP code for a function called getMyValue() that involves “expensive” calculations. Here “expensive” means it slows down our application (e.g. a remote API call or something computationally complex).

function get_my_value() {
  // Lots of "expensive" calculations to determine $my_value;
  return $my_value;
}

Applying a Filter Sub-Optimally

One way that we could apply a WordPress filter is to run our result through apply_filters() in our return statement. e.g.

function get_my_value() {
  $my_value = expensive_calculation_function();
  return apply_filters(
    'salcode_my_value',
    $my_value
  );
}

This accomplishes the basic goal of allowing outside code to overwrite the value returned by get_my_value().

However, it has the disadvantage that even though we no longer use $my_value we still go through the “expensive” calculations to determine it (maybe this is a remote API call or requires lots of math but whatever it is it slows down our application).

Applying a Filter with the Early Return Pattern

The advantage of the early return pattern is if we get a value from the filter, we skip our own “expensive” calculations.

Early Return Pattern Example

function get_my_value() {
  $my_value = apply_filters(
    'salcode_my_value',
    null
  );
  if ( ! is_null( $my_value ) ) {
    // A value was provided via WP filter, return early.
    return $my_value;
  );

  $my_value = expensive_calculation_function();
  return $my_value;
}
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Computing, Dev Tips, Draft, Programming Tagged With: WordPress, WordPress Filter

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in