按多个元键和元值排序

时间:2016-11-16 作者:Dhiraj Suthar

如何按元值顺序设置多个元键,有谁能给我举个例子吗?

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

meta_query 是元子句的数组。例如:

$q = new WP_Query( array(
    \'meta_query\' => array(
        \'relation\' => \'AND\',
        array(
            \'key\' => \'state\',
            \'value\' => \'Wisconsin\',
        ),
        array(
            \'key\' => \'city\',
            \'compare\' => \'EXISTS\',
        ), 
    ),
) );
可以使用关联数组,每个meta子句都有一个键:

$q = new WP_Query( array(
    \'meta_query\' => array(
        \'relation\' => \'AND\',
        \'state_clause\' => array(
            \'key\' => \'state\',
            \'value\' => \'Wisconsin\',
        ),
        \'city_clause\' => array(
            \'key\' => \'city\',
            \'compare\' => \'EXISTS\',
        ), 
    ),
) );
然后,您可以在order_by 参数,带一个:

$q = new WP_Query( array(
    \'meta_query\' => array(
        \'relation\' => \'AND\',
        \'state_clause\' => array(
            \'key\' => \'state\',
            \'value\' => \'Wisconsin\',
        ),
        \'city_clause\' => array(
            \'key\' => \'city\',
            \'compare\' => \'EXISTS\',
        ), 
    ),
    \'orderby\' => \'city_clause\', // Results will be ordered by \'city\' meta values.
) );
或更多条款:

$q = new WP_Query( array(
    \'meta_query\' => array(
        \'relation\' => \'AND\',
        \'state_clause\' => array(
            \'key\' => \'state\',
            \'value\' => \'Wisconsin\',
        ),
        \'city_clause\' => array(
            \'key\' => \'city\',
            \'compare\' => \'EXISTS\',
        ), 
    ),
    \'orderby\' => array( 
        \'city_clause\' => \'ASC\',
        \'state_clause\' => \'DESC\',
    ),
) );
示例取自this post 在Make WordPres核心博客中。