If you’re going to add the filter on the where clause, then just make sure you remove it using remove_filter() and the exact same signature immediately after you create the query.
In your example, you’re using query_posts(), so add the filter, run your query, and then remove your filter right afterward.
add_filter( 'posts_where', 'my_posts_where_filter', 10, 2 );
query_posts( $query_string );
remove_filter( 'posts_where', 'my_posts_where_filter', 10, 2 );
It is to be noted that when you use the 2-argument version, the second argument can be of great use in limiting your filter to only affecting the queries you’re interested in.
add_filter( 'posts_where', 'my_posts_where_filter', 10, 2 );
function my_posts_where_filter( $where_clause, $query_object ){
// check conditions on your query object...
// ... then manipulate your $where_clause accordingly
return $where_clause;
}
If you go that route, you can probably dispense with the remove_filter() altogether.
Further, you can probably dispense with query_posts()
too, while you’re at it. if you’re already mucking around with get_posts()
filters, which are run on every query, adding in another query with query_posts()
is just going to slow down your blog load times.
So find a way to identify the page you’re on (inspect the $query_object using print_r()
to see what goodies it holds, or use a conditional like is_main_query()
etc), then wrap your additional WHERE
conditions within a big ol’ if{ }
block. Set up your filter NOT from the page template you’re on, but rather from within your functions.php
, or some included class. And of course test, test, test to make sure you’re not affecting other pages of your site, or some widget, or your RSS feed, or the admin back end.