Title: Sorting on multiple custom fields
Last modified: August 20, 2016

---

# Sorting on multiple custom fields

 *  [tvfc](https://wordpress.org/support/users/tvfc/)
 * (@tvfc)
 * [14 years, 2 months ago](https://wordpress.org/support/topic/sorting-on-multiple-custom-fields/)
 * Hi,
 * I’m creating a site for a football team, and am trying to create a league table
   where all the values are stored into custom fields.
 * When I’m displaying this on, I cannot find a way of sorting by 2 custom fields
   together (ie, if points are equal, sort by goal difference). I have followed 
   though this article ([http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query](http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query))
   but I can’t work out how to modify it to query/sort both.
 * Any suggestion’s welcome – my custom field name’s are ‘pts’ and ‘goal-diff’, 
   and are stored in a custom post type ‘league-table’.
 * Thanks – Paul.

Viewing 1 replies (of 1 total)

 *  [vtxyzzy](https://wordpress.org/support/users/vtxyzzy/)
 * (@vtxyzzy)
 * [14 years, 2 months ago](https://wordpress.org/support/topic/sorting-on-multiple-custom-fields/#post-2620760)
 * I do not have a way to test this, but I think this query is what you want:
 *     ```
       $querystr = "
           SELECT $wpdb->posts.*,pt.meta_value as pts, goal.meta_value as goal_diff
           FROM $wpdb->posts, $wpdb->postmeta pt, $wpdb->postmeta goal
           WHERE $wpdb->posts.ID = pt.post_id
           AND pt.meta_key = 'pts'
           AND $wpdb->posts.ID = goal.post_id
           AMD goal.meta_key = 'goal-diff'
           AND $wpdb->posts.post_status = 'publish'
           AND $wpdb->posts.post_type = 'league-table'
           AND $wpdb->posts.post_date < NOW()
           ORDER BY pts + 0 ASC, goal_diff + 0 ASC, UPPER($wpdb->posts.post_title) ASC
        ";
       ```
   

Viewing 1 replies (of 1 total)

The topic ‘Sorting on multiple custom fields’ is closed to new replies.

## Tags

 * [custom sort](https://wordpress.org/support/topic-tag/custom-sort/)

 * In: [Fixing WordPress](https://wordpress.org/support/forum/how-to-and-troubleshooting/)
 * 1 reply
 * 2 participants
 * Last reply from: [vtxyzzy](https://wordpress.org/support/users/vtxyzzy/)
 * Last activity: [14 years, 2 months ago](https://wordpress.org/support/topic/sorting-on-multiple-custom-fields/#post-2620760)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
