0

I'm adding a filter for a WordPress query in a widget. I'm adding as following:

function filter_where( $where = '' ) {

}
add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $args );
remove_filter( 'posts_where', 'filter_where' );

It works fine, but if I use the same widget more than 1 times then I get the fatal error that the same filter cannot be re-declared. How can I use the filter so that the same widget can be used multiple times?

This is the exact error I get:

Fatal error: Cannot redeclare filter_where() (previously declared in xxx.php:70)

Thanks.

3
  • Can you be more specific? What does the Fatal error say. It sounds like the function thinks it's being defined twice? Maybe a if ( !function_exists('filter_where')) {} wrapper would do the trick. Commented Jan 21, 2014 at 21:14
  • @EricHolmes I have updated the question, please check.
    – enam
    Commented Jan 21, 2014 at 21:27
  • It's looking like a namespace issue. Try changing it to enam_filter_where in both your add/remove filter statements, and the function definition - still get the error? A plugin you have may have the same function name. Commented Jan 21, 2014 at 21:29

2 Answers 2

1

Your code should look something like this:

class my_Widget extends WP_Widget {

...

function filter_where( $where = '' ) {
    ...
}

function widget( $options ) {
    ...
    add_filter( 'posts_where', array( $this, 'filter_where' ) );
    $query = new WP_Query( $args );
    remove_filter( 'posts_where', array( $this, 'filter_where' ) );
}
}

This will keep the function within your class, access it at a class level, and avoid any namespace issues.

0
0

You must be defining your callback function inside a function that is reused by the widget system-- my guess is inside the widget method.

Define the callback outside the widget itself, and only apply (apply_filter) inside the widget.

In other words, add your callback as class method, and add it something like this:

add_filter('posts_where', array($this,'filter_where'));

You should be able to remove it with a similar syntax.

Without seeing your code in context that is the best I've got.

2
  • Thanks for the answer. Yes, I'm using it in the widget method, as you can see above that I added it just before the WP_Query and removed it after that. Could you please give an example of adding and removing it outside the widget method.
    – enam
    Commented Jan 21, 2014 at 21:28
  • @enam : see the edit.
    – s_ha_dum
    Commented Jan 21, 2014 at 21:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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