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;
}
Leave a Reply