是否可以在meta_key's
中添加两个pre_get_posts
?
我当前的查询
$query->set('s', '' );
$query->set( 'meta_key', 'cat_adresse_stadtteil' );
$query->set( 'meta_value', array('charlottenburg', 'wilmersdorf', 'schmargendorf') );
添加此
$query->set('orderby','meta_value_num');
$query->set('meta_key', 'rank');
$query->set('order', 'ASC');
的修改
好的,我找到了这个解决方案(link #example 2)
$args = array(
'numberposts' => -1,
'post_type' => 'event',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'location',
'value' => 'Melbourne',
'compare' => '='
),
array(
'key' => 'attendees',
'value' => 100,
'type' => 'NUMERIC',
'compare' => '>'
)
)
);
但它不起作用,任何想法出了什么问题?
$query->set('meta_query',array(
array( 'key' => 'cat_adresse_stadtteil',
'value' => array('charlottenburg', 'wilmersdorf', 'schmargendorf'), ),
array( 'key' => 'rank'
'orderby' => 'meta_value_num',
'order' => 'ASC' ) ) );
答案 0 :(得分:15)
要合并这两部分,您可以尝试以下方法:
add_action( 'pre_get_posts', function( $q ) {
// Only modify the main query on the front-end:
if( ! is_admin() && $q->is_main_query() )
{
$meta_query = array(
array(
'key' => 'cat_adresse_stadtteil',
'value' => array('charlottenburg', 'wilmersdorf', 'schmargendorf'),
'compare' => 'IN',
),
);
$q->set( 'meta_query', $meta_query );
$q->set( 'meta_key', 'rank' );
$q->set( 'orderby', 'meta_value_num' );
$q->set( 'order', 'ASC' );
$q->set( 's', '' );
}
});
您似乎错过了compare
参数,并在错误的位置使用了order
和orderby
参数。我不确定你为什么要重置搜索参数。
生成的SQL查询类似于:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta
ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1
ON (wp_posts.ID = mt1.post_id)
WHERE 1=1
AND wp_posts.post_type
IN ('post', 'page', 'attachment' )
AND (wp_posts.post_status = 'publish'
OR wp_posts.post_author = 1
AND wp_posts.post_status = 'private')
AND (wp_postmeta.meta_key = 'rank'
AND (mt1.meta_key = 'cat_adresse_stadtteil'
AND CAST(mt1.meta_value AS CHAR)
IN ('charlottenburg','wilmersdorf','schmargendorf')) )
GROUP BY wp_posts.ID
ORDER BY wp_postmeta.meta_value+0 ASC
LIMIT 0, 10
答案 1 :(得分:4)
您可以将此查询转换为pre_pget_posts:
$meta_query_args = array(
'relation' => 'AND', // "OR"
array(
'key' => '_my_custom_key',
'value' => 'Value I am looking for',
'compare' => '='
),
array(
'key' => '_your_min_model_key',
'value' => 1453,
'compare' => '>'
),
array(
'key' => '_your_max_model_key',
'value' => 1923,
'compare' => '<'
)
);
$meta_query = new WP_Meta_Query( $meta_query_args );
比较参数详情:
compare (string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' (only in WP >= 3.5), and 'NOT EXISTS' (also only in WP >= 3.5). Values 'REGEXP', 'NOT REGEXP' and 'RLIKE' were added in WordPress 3.7. Default value is '='.