Check if a filter or function has been already been called

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

Leave a Comment