1

wordpress wpdb クラスを使用して、メタ キーの 2 つの値のいずれかでカスタム投稿を返し、それらの投稿を 3 番目のメタ値で並べ替えようとしています。必要な投稿を取得できますが、希望どおりに並べ替える方法がわかりません。

私がこれまで持っている機能は次のとおりです。

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

アーティストの姓に対して 2 つ目の結合を行う必要があります。

別の推奨事項は、次のように、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 に答える