Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I can read on the docs that if I need to perform a custom WHERE on WP_Query I need to do the following:

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
    // posts  30 to 60 days old
    $where .= " AND post_date >= '" . date('Y-m-d', strtotime('-60 days')) . "'" . " AND post_date <= '" . date('Y-m-d', strtotime('-30 days')) . "'";
    return $where;
}

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

BUT what If I need to apply such a WHERE condition on the default query? I already have other conditions being applied during a pre_get_posts, something like this:

function homepage_load_posts($query) {
  if ($query->is_home()) {
    $params = querystring_var('filter'); 

    $query->query_vars['post_type'] = array('blog_post', 'post', 'dossier'); 
    $query->query_vars['posts_per_page'] = 12; 

    if ($params) {
      $valid_categories = valid_categories($params['cat']);
      $valid_formats    = valid_formats($params['format']);
      $valid_post_types = valid_post_types($params['type']);

      if ($valid_categories) $query->query_vars['cat'] = $valid_categories; 
      if ($valid_formats)    $query->query_vars['tax_query'] = $valid_formats; 
      if ($valid_post_types) $query->query_vars['post_type'] = $valid_post_types;

    }
  }
}

add_action('pre_get_posts', 'homepage_load_posts');
share|improve this question

1 Answer 1

up vote 1 down vote accepted

The posts_where filter should still fire. Just add it like this:

function homepage_load_posts($query) {
  if ($query->is_home()) {
    add_filter( 'posts_where', 'filter_where' );
    //

And make the filter self-removing...

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
    remove_filter( 'posts_where', 'filter_where' );
    // posts  30 to 60 days old
    $where .= " AND post_date >= '" . date('Y-m-d', strtotime('-60 days')) . "'" . " AND post_date <= '" . date('Y-m-d', strtotime('-30 days')) . "'";
    return $where;
}
share|improve this answer
    
yes it works thanks! I suspect I was doing something wrong like using add_action instead of add_filter :\ –  Fabrizio Regini Jul 19 '13 at 8:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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