Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I would like to filter get_terms(), but I only want to filter get_terms() when it is called from the wp_terms_checklist() function.

I am looking to add a "No term" option to the end of my checklist (radio buttons actually as this pertains to my Radio Buttons for Taxonomies plugin). I have already done this but find it produces some PHP notices in the restrict_manage_posts hook, so I was wondering if there was a way to limit the application of the filter.

share|improve this question
    
Can you use debug_backtrace() to get a call stack and then check whether the function you want is included? –  anu Apr 17 at 9:56
    
Maybe? I'm not familiar with that function, so I will have to check it out. –  helgatheviking Apr 17 at 10:02

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
hehe beat me to it, I had similar idea in my unpublished answer (+1) –  birgire Apr 17 at 10:29
1  
@birgire be faster next time ;) –  G. M. Apr 17 at 10:33
1  
I had to tweak it for use in multiple classes (basically just switched $set to a class property, but the concept is on the money. Thanks! –  helgatheviking Apr 17 at 11:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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