admin管理员组

文章数量:1416309

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).

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).

Share Improve this question asked Aug 14, 2019 at 2:56 Jess_PinkmanJess_Pinkman 3361 silver badge5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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();
    }
}

本文标签: plugin developmentmultiple functions with same filter