2

I want to use the same filter hook in different locations, and I just want to make sure this is OK to do so ( preliminary test shows it works, but I am not 100% sure it is OK to do so).

So the add_filter('check_powers', .... ) is in one location only ( not that it matters)

function define_user_powers()
{
  if ( user_is_powerful() ){
    add_filter('check_powers', 'give_super_power');
  }
}

function give_super_power( $powers ){
  $powers = true;
  return $powers;
}

But the apply_filters('check_powers') is in several locations:

function kick_ass()
{
  $powers = apply_filters('check_powers', false );
  if ( $powers ) {
   do_smthng();
  }

}

function fly()
{
  $powers = apply_filters('check_powers', false );
  if ( $powers ) {
   do_smthng_else();
  }
}

All questions i have found relates to the other way around ( multiple add_filter to same hook).

1

There's nothing technically wrong with this. It will work, but it's very important to make sure the usage of the filter is consistent everywhere it's used, otherwise you could experience issues.

My suggestion would be to abstract the powers check into a separate function, and use the filter there. For example, the filter could be inside user_is_powerful(), and then you check that function wherever you need to:

function user_is_powerful() {
    $is_powerful = false;

    // Do stuff.

    return apply_filters( 'check_powers', $is_powerful );
}

function kick_ass() {
    $powers = user_is_powerful();

    if ( $powers ) {
        do_smthng();
    }
}

function fly() {
    $powers = user_is_powerful();

    if ( $powers ) {
        do_smthng_else();
    }
}
  • Thanks, my context is actually quite different, but glad to know that it is OK to do so, (with proper implementation). – Jess_Pinkman Aug 14 at 3:21

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.