简体   繁体   中英

Custom select query wordpress order by meta key value

I am trying to ORDER BY my results of a custom select query.

But I am trying to order by the value of a meta key.

Please see my query below...

$get_atts =  $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE $wpdb->posts.post_type IN ('individual') ORDER BY $wpdb->posts.meta_key = 'surname' ASC");

As you can see this ORDER BY is breaking it...

ORDER BY $wpdb->posts.meta_key = 'surname' ASC"

So I am trying to order by the value of surname

But my does not seem to work. Can any explain why or help?

Try to use this query:

$get_atts =  $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts, $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = 'surname' 
    AND $wpdb->posts.post_type IN ('individual') ORDER BY $wpdb->postmeta.meta_value ASC");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM