Is there a way in WordPress to check, on a screen load, if a filter has been called or a function has run?
I seem to recall some way to do that, but don’t recall the specifics.
A filter is being called 3 times during a page load and I want to check if it has already been called before I run various db intensive code again.
My questions is not specific to the_content
, but for example:
add_filter( 'the_content', 'asdf_the_content', 99, 1 );
function asdf_the_content( $content ) {
// check if the_content has already been
// filtered by some other function
$content = ucwords( $content );
return $content;
}
1
You can use a static variable to achieve this:
add_filter( 'the_content', 'asdf_the_content', 99, 1 );
function asdf_the_content( $content ) {
static $has_run = false;
if ( $has_run ) {
return $content;
}
$has_run = true;
// check if the_content has already been
// filtered by some other function
$content = ucwords( $content );
return $content;
}
The $has_run
variable will be false
on the first run, and subsequent runs it will be true
and the code will not continue. Static variables like this inside a function maintain their values during each execution, instead of initializing like normal variables.
Another example:
function add_one() {
static $total = 0;
$total++;
echo $total;
}
add_one(); // 1
add_one(); // 2
add_one(); // 3