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.

1 Answer
1

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.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *