Display Posts by modifying the where clause only for my query

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?

1 Answer
1

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.

Leave a Comment