当前查询
$args = array(
\'post_type\' => \'brands\',
\'meta_query\' => array(
array(
\'key\' => \'br_type\',
\'value\' => \'Aviation\'
),
array(
\'key\' => \'br_category\'
),
array(
\'key\' => \'br_name\'
)
),
\'posts_per_page\' => -1,
\'orderby\' => [ \'br_category\' => \'ASC\', \'br_name\' => \'ASC\' ],
\'order\' => \'ASC\',
\'fields\' => \'ids\'
);
生成此SQL查询
\'SELECT 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 ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) WHERE 1=1
AND (
( wp_postmeta.meta_key = \\\'br_type\\\' AND wp_postmeta.meta_value = \\\'Aviation\\\' )
AND
mt1.meta_key = \\\'br_category\\\'
AND
mt2.meta_key = \\\'br_name\\\'
) AND wp_posts.post_type = \\\'brands\\\' AND (wp_posts.post_status = \\\'publish\\\' OR wp_posts.post_status = \\\'acf-disabled\\\' OR wp_posts.post_author = 1 AND wp_posts.post_status = \\\'private\\\') GROUP BY wp_posts.ID \'
这意味着它不添加任何order by子句,因为它不理解。
下面是按多个元键值排序的正确方法
$args = array(
\'post_type\' => \'brands\',
\'meta_query\' => array(
// \'relation\' => \'AND\', // default is AND
\'br_type_clause\' => array(
\'key\' => \'br_type\',
\'value\' => \'Aviation\',
),
\'br_category_clause\' => array(
\'key\' => \'br_category\',
),
\'br_name_clause\' => array(
\'key\' => \'br_name\',
)
),
\'posts_per_page\' => -1,
\'meta_key\' => array( \'br_category\', \'br_name\', \'br_type\' ),
// add sql: wp_postmeta.meta_key IN (\'br_category\',\'br_name\',\'br_type\')
\'orderby\' => array(
\'br_type_clause\' => \'ASC\',
\'br_category_clause\' => \'ASC\',
\'br_name_clause\' => \'ASC\',
\'name\' => \'ASC\', // illustrative purpose, could use post key
),
// \'order\' => \'ASC\', // it is ignored with above orderby override
\'fields\' => \'ids\'
),
产生SQL
SELECT 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 ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id ) WHERE 1=1 AND (
wp_postmeta.meta_key IN (\'br_category\',\'br_name\',\'br_type\')
AND
(
( mt1.meta_key = \'br_type\' AND mt1.meta_value = \'Aviation\' )
AND
mt2.meta_key = \'br_category\'
AND
mt3.meta_key = \'br_name\'
)
) AND wp_posts.post_type = \'brands\' AND (wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'acf-disabled\' OR wp_posts.post_author = 1 AND wp_posts.post_status = \'private\') GROUP BY wp_posts.ID ORDER BY CAST(mt1.meta_value AS CHAR) ASC, CAST(mt2.meta_value AS CHAR) ASC, CAST(mt3.meta_value AS CHAR) ASC, wp_posts.post_name ASC
参考号:
WP_Query 带截面
‘orderby’ with multiple ‘meta_key’s