2

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
    Can you include a code example of exactly what you're talking about? – Jacob Peattie Aug 30 at 11:44
  • I'm asking if there is a WP method for doing so. Not a solution to a specific filter. And I know about remove_filter. But I've added a generic filter call above. – shanebp Aug 30 at 15:19
  • I’m more interested in why you need to check if the filter has run. What are you trying to avoid repeating. I basically want to see if a transient or the object is really what you need, rather than actually knowing about the filter. – Jacob Peattie Aug 30 at 15:47
  • It's function that includes a filter for an ajax query string. If I use the filter hook and log the calls, it runs 3 times. I cannot stop that, but I hoped there was a native WP way to check if a call to that filter had already been made. I know about transients, etc. – shanebp Aug 30 at 16:01
3

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
  • 1
    Thanks. remove_filter also works. But I like the static var approach and had forgotten about it. – shanebp Aug 30 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.