WP_QUERY具有多个元查询语句和ORDER BY META_VALUE

时间:2013-05-28 作者:Richard B

这是我的问题:

$the_query = new WP_Query(
    array (
        \'post_type\'         => \'pass\',
        \'posts_per_page\'    => \'-1\',
        \'post_status\'       => \'publish\',
        \'orderby\'           => \'meta_value\',
        \'meta_key\'          => \'start_time\',
        \'order\'             => \'ASC\',
        \'meta_query\'        => array(
            \'relation\'      => \'OR\',
            array(
                \'key\'       => \'event\',
                \'value\'     => $tmp_posts->ID,
                \'compare\'   => \'==\'
            ),
            array(
                \'key\'       => \'meeting_type\',
                \'value\'     => \'other\',
                \'compare\'   => \'!=\'
            )
        )
    )
);
我的问题是这个查询没有按start\\u时间对帖子排序。如果我删除了第二个meta\\u查询数组(以及“relation”=>“OR”),那么orderby工作得很好。为什么会这样?

如果I var\\u dump$the\\u query,这就是输出的查询:

SELECT wp_posts.*
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_posts.post_type = \'pass\'
    AND (wp_posts.post_status = \'publish\')
    AND (wp_postmeta.meta_key = \'start_time\'
        OR (mt1.meta_key = \'event\'
        AND CAST(mt1.meta_value AS CHAR) = \'10011\'
    )
    OR (
        mt2.meta_key = \'meeting_type\'
        AND CAST(mt2.meta_value AS CHAR) != \'other\')
    )
GROUP BY wp_posts.ID
ORDER BY wp_postmeta.meta_value ASC
我怎样才能在start\\u时间前将此文件排序?

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

我无法创建WP\\u查询–我认为使用常规WP\\u查询无法解决此问题–但我成功创建了一条SQL语句,该语句完全符合我的要求:

SELECT wp_posts.*
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 = \'pass\'
    AND (wp_posts.post_status = \'publish\')
    AND (
        wp_postmeta.meta_key = \'start_time\'
        AND (
            (
                mt1.meta_key = \'event\'
                AND CAST(mt1.meta_value AS CHAR) = \'10011\'
            )
            OR (
                mt1.meta_key = \'meeting_type\'
                AND CAST(mt1.meta_value AS CHAR) != \'other\'
            )
        )
    )

GROUP BY wp_posts.ID
ORDER BY wp_postmeta.meta_value ASC

结束