I am trying to display posts that are 7 days old. For that i need to modify the ‘where’ clause as in code
//Hack found on the bottom of http://codex.wordpress.org/Template_Tags/query_posts
function filter_where($where = '') {
//posts in the last 7 days
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-7 days')) . "'";
}
('posts_where', 'filter_where');
query_posts($query_string);
if ( have_posts() ) : while ( have_posts() ) : the_post();
... and the usual
But doing this will modify all the queries, i just want to use this for one query in my plugin and i dont want to change any other query on my site. How can i do that?
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.
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.
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 withget_posts()
filters, which are run on every query, adding in another query withquery_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 likeis_main_query()
etc), then wrap your additionalWHERE
conditions within a big ol’if{ }
block. Set up your filter NOT from the page template you’re on, but rather from within yourfunctions.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.