我可以从文档中了解到,如果我需要执行自定义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\');
最合适的回答,由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;
}