在PRE_POST_QUERY中使用多个元键

时间:2017-04-13 作者:Joe Fawley

我已经根据pre\\u get\\u posts中的查询字符串筛选了一些自定义帖子:

if( $query->is_main_query() ) {
    if( is_post_type_archive( \'events\' ) ) {
        if ($_GET[\'status\']) {
            $retrieved_status = $_GET[\'status\'];
            $query->set(\'meta_key\', \'event_status\');
            $query->set(\'meta_value\', $retrieved_status);
        }
    }
}
然后,我还想按不同的自定义字段进行排序,但我不能使用以下内容,因为它会重写meta\\u键:

$query->set(\'orderby\', \'meta_value\');   
$query->set(\'meta_key\', \'event_date\');   
$query->set(\'order\', \'DESC\');
我如何构建此结构以获得所需的效果?谢谢

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

使用WP\\u Query根据元键和值选择任何帖子。您还可以对帖子进行排序,例如:

$args = array(
    \'post_type\'  => \'events\',
    \'orderby\'   => \'meta_value_num\', //probably you will need this because the value is date
    \'meta_key\'  => \'event_date\',
    \'meta_query\' => array(
        \'relation\'  => \'AND\',
        array(
            \'key\'     => \'event_status\',
            \'value\'   => $retrieved_status, 
            \'compare\' => \'=\',
        ),
        array(
            \'key\' => \'other_key\',
            \'value\'   => \'other_value\',
            \'type\'    => \'numeric\', //for example
            \'compare\' => \'BETWEEN\', //for example
        ),
    ),
);
$query = new WP_Query( $args );
请参见Order & Orderby Parameters &;对于meta_value_num 看见Custom Field Parameters

SO网友:Howdy_McGee

WP\\U查询有一个称为Meta Query 您可以根据需要传递任意多个复杂参数:

$query = new WP_Query array(
    \'meta_query\'    => array(
        \'relation\'  => \'AND\',       // OR is the default relation parameter, if this is excluded
        array(
            \'key\'       => \'meta_key_one\',
            \'value\'     => \'meta_value_one\',
            \'compare\'   => \'<=\',
        ),
        array(
            \'key\'       => \'meta_key_two\',
            \'value\'     => \'meta_value_two\',
            \'compare\'   => \'<=\',
        ),
    ),
) );
上面说:

SELECT
    All Posts
    WHERE
    Meta Keys Value One is Less Than or Equal to Passed Value One
    AND
    Meta Keys Value Two is Less Than or Equal to Passed Value Two

相关推荐

如何让`wp-list-table`显示我在Custom-Post中的`Custom-Fields`

一切都好吗<我需要wp-list-table 也要显示custom-fields 在每个custom-post 我有,但我不知道如何做到这一点,在这幅图中,它显示了带有字段的表格:Title, Author and Publication Date: 我想要的是能够选择custom-fields 将出现,例如以下示例Title, Carta, Naipe, Author, and Date of Publication: