Restrict filter to run only inside specific function

wp_terms_checklist early trigger a filter 'wp_terms_checklist_args' so you can use that filter to add your filter and auto-remove it haver 1st run.

This should be enough, however, once hooks are global variables, to be sure is better use some stronger check, a static variable inside a function is a simple and nice trick:

function switch_terms_filter( $_set = NULL ) {
  static $set;
  if ( ! is_null($_set) ) $set = $_set;
  return $set;
}

add_filter( 'wp_terms_checklist_args', function( $args ) {

  // turn the switch ON
  switch_terms_filter(1);

  add_filter( 'get_terms', 'your_filter_callback', 10, 3 );

  return $args; // we don't want to affect wp_terms_checklist $args
} );


function your_filter_callback( $terms, $taxonomies, $args ) {
  // remove filter after 1st run
  remove_filter( current_filter(), __FUNCTION__, 10, 3 );

  // is the switch ON? If not do nothing.
  if ( switch_terms_filter() !== 1 ) return $terms;

  switch_terms_filter(0); // turn the switch OFF

  // ... filter terms here ...
  return $terms;
}

Untested.

Leave a Comment