How To Dual-Sort Query Results In WordPress Using get_posts
erics, September 12th, 2019
Needed to build a feature for a Bookstore tool to have an optional sequence number for the Custom Post Type “books” that would allow items with a seq number to float to the top of the list and be sorted by seq #. The rest of the books would show underneath, sorted alphabetically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
$querytop = get_posts(array( 'post_type' => 'books', 'numberposts' => -1, 'orderby' => 'meta_value', 'meta_key' => 'book_seq', 'order' => 'ASC', 'meta_query' => array( // meta query takes an array of arrays, watch out for this! array( 'key' => 'book_seq', 'value' => array('', 'NULL'), 'compare' => 'NOT IN' ) ) )); $querybottom = get_posts(array( 'post_type' => 'books', 'numberposts' => -1, 'orderby' => 'post_title', 'order' => 'ASC', 'meta_query' => array( // meta query takes an array of arrays, watch out for this! array( 'key' => 'book_seq', 'compare' => 'NOT EXISTS' ) ) )); $query = array_merge($querytop, $querybottom); |