1

我正在尝试使用 wordpress wpdb 类返回具有元键的两个值之一的自定义帖子,然后按第三个元值对这些帖子进行排序。我可以得到我想要的帖子,但我似乎无法弄清楚如何按照我想要的方式对它们进行排序。

我到目前为止的功能是:

function artists_search_country($country_alt){
    global $wpdb;
    $querystr = "
        SELECT wposts.*
        FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
        WHERE wposts.ID = wpostmeta.post_id
        AND ((wpostmeta.meta_key = '_artist_country' AND wpostmeta.meta_value = '$country_alt')
        OR (wpostmeta.meta_key = '_artist_country_sub' AND wpostmeta.meta_value = '$country_alt'))
        AND wposts.post_type = 'artists'
        AND wposts.post_status = 'publish'
    ";
    $myposts = $wpdb->get_results($querystr, OBJECT);
    return $myposts;
}

我想做类似的事情:

function artists_search_country($country_alt){
    global $wpdb;
    $querystr = "
        SELECT wposts.*
        FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
        WHERE wposts.ID = wpostmeta.post_id
        AND ((wpostmeta.meta_key = '_artist_country' AND wpostmeta.meta_value = '$country_alt')
        OR (wpostmeta.meta_key = '_artist_country_sub' AND wpostmeta.meta_value = '$country_alt'))
        AND wposts.post_type = 'artists'
        AND wposts.post_status = 'publish'
        ORDER BY (wpostmeta.meta_key = '_artist_artist_last_name' AND wpostmeta.value) ASC
    ";
    $myposts = $wpdb->get_results($querystr, OBJECT);
    return $myposts;
}

请原谅ORDER BY在线上糟糕的语法,但我只是不知道如何处理这个,我尝试的一切都会破坏查询。任何帮助将不胜感激,因为我对 SQL 查询没有太多经验。

4

1 回答 1

1

试试这个 SQL 语句:

SELECT wposts.*, l.meta_value as artist_last_name
FROM $wpdb->posts wposts
    join $wpdb->postmeta wpostmeta
    on wposts.ID = wpostmeta.post_id
    join $wpdn->postmeta l
    on wposts.ID = l.post_id
    and l.meta_key = '_artist_artist_last_name'
WHERE
(( wpostmeta.meta_key = '_artist_country' AND wpostmeta.meta_value = '$country_alt')
OR (wpostmeta.meta_key = '_artist_country_sub' AND wpostmeta.meta_value = '$country_alt') )
AND wposts.post_type = 'artists'
AND wposts.post_status = 'publish'
ORDER BY l.meta_value ASC

您需要为艺术家的姓氏进行第二次加入。

另一个建议是利用 Wordpress 的$wpdb->prepare,如下所示:

$querystr = "
SELECT wposts.*, l.meta_value as artist_last_name
FROM $wpdb->posts wposts
    join $wpdb->postmeta wpostmeta
    on wposts.ID = wpostmeta.post_id
    join $wpdn->postmeta l
    on wposts.ID = l.post_id
    and l.meta_key = '_artist_artist_last_name'
WHERE
(( wpostmeta.meta_key = '_artist_country' AND wpostmeta.meta_value = %s)
OR (wpostmeta.meta_key = '_artist_country_sub' AND wpostmeta.meta_value = %s) )
AND wposts.post_type = 'artists'
AND wposts.post_status = 'publish'
ORDER BY l.meta_value ASC
";
$myposts = $wpdb->get_results($wpdb->prepare( $querystr, $country_alt, $country_alt ), OBJECT);

希望这可以帮助。

于 2012-05-11T21:01:08.193 回答