2012-04-18 75 views
1

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

我迄今为止的功能是:

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查询经验。

回答

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); 

希望这有助于。