将定制的WHERE应用于默认的$wp_Query

时间:2013-07-18 作者:Fabrizio Regini

我可以从文档中了解到,如果我需要执行自定义WHERE on WP\\u查询,我需要执行以下操作:

// 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 如果需要对默认查询应用这样的WHERE条件,该怎么办?我已经在pre_get_posts, 类似这样:

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\');

1 个回复
最合适的回答,由SO网友:s_ha_dum 整理而成

这个posts_where 过滤器仍应着火。只需这样添加即可:

function homepage_load_posts($query) {
  if ($query->is_home()) {
    add_filter( \'posts_where\', \'filter_where\' );
    //
并使过滤器自动删除。。。

// 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;
}

结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post