具有多个关系键的嵌套meta_query


18

我很好奇Wordpress是否可以嵌套运行meta_query,每个都有不同的关系键?从Wordpress 3.0开始,tax_query可以执行此功能;我想知道这是否与等效meta_query

$results = query_posts( array(
    'post_type' => 'event_id',
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'relation' => 'OR',
            array(
                'key' => 'primary_user_id',
                'value' => $user_id
            ),
            array(
                'key' => 'secondary_user_id',
                'value' => $user_id
            )
        ),
        array(
            'key' => 'date',
            'value' => array( $start_date, $end_date ),
            'type' => 'DATETIME',
            'compare' => 'BETWEEN'
        )
    )
) );

参考文献:

Answers:



9

这似乎是不可能的。如果我错了,请有人纠正我。

meta_query参数将切实转化为一个WP_Meta_Query对象,并且relation验证不会去更深wp-includes/meta.php,并且出现只有一次在顶级:

if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
    $this->relation = 'OR';
} else {
    $this->relation = 'AND';
}

一个可能的解决方案是为此查询建立自己的JOIN。

$query = new WP_Query( array(
    ...
    'my_meta_query' => true,
    'suppress_filters' => false
) );

add_filter( 'posts_join', 'my_meta_query_posts_join', 10, 2 );
function my_meta_query_posts_join( $join, $query ) {

    if ( empty( $query->query_vars['my_meta_query'] ) )
        return $join;

    global $wpdb;

    $new_join = "
        INNER JOIN {$wpdb->postmeta} pm1 ON 1=1
            AND pm1.post_id = {$wpdb->posts}.ID
            AND pm1.meta_key = '_some_meta_key'
            AND pm1.meta_value = 'some_value'
    ";

    return $join . ' ' . $new_join;
}

并且,如果您需要进一步的验证和规则,也可以使用posts_where过滤器。


3
似乎是@scribu在Core Trac上推荐的相同方法:core.trac.wordpress.org/ticket/20312
Andrew Odri 2014年

@AndrewOdri一样,但不是=)
vmassuchetto

1

同时,这是可能的,请参见带有示例和说明的文档:

https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

和另一个示例https://wordpress.org/support/topic/wp_query-with-multiple-meta_query/#post-9410992

'meta_query'  => array(
    'relation' => 'OR',
    array(
        'relation' => 'AND',
        array(
            'key'     => '_price',
            'value'   => 1,
            'compare' => '>=',
            'type' => 'DECIMAL',
        ),
        array(
            'key'     => '_price',
            'value' <= 3000,
            'compare' => '<=',
            'type' => 'DECIMAL',
        ),
    ),
    array(
        'relation' => 'AND',
        array(
            'key'     => '_price',
            'value'   => 3001,
            'compare' => '>=',
            'type' => 'DECIMAL',
        ),
        array(
            'key'     => '_price',
            'value' <= 6000,
            'compare' => '<=',
            'type' => 'DECIMAL',
        ),
    )
),
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.