OrderBy multiple meta_key ?
-
Wonder if anyone can point me in the right direction on an issue I’m trying to solve. Or if it is even possible.
I have a custom post type that I’m listing in a WP_Query loop. I know how to make it orderby a meta_key/meta_value_num, but what I’m wondering is. Can I order by multiple meta_keys?
For Example.
I have two custom fields (field1 & field2), field1 with 2 possible values (valueA or valueB), and field2 being a text input. I need it to split the entire list so it shows first all posts with field1(valueA), then follows with all posts with field1(valueB). Then in each division it orders them by field2 value (meta_value_num).I was thinking about creating multiple loops, but then pagination becomes an issue. Also I have played with meta_query, but that just seems to get posts with multiple fields, it doesn’t sort them by the multiple fields.
My Initial Attempt:
$cat = get_term_by('name', single_cat_title('',false), 'post-category'); $cname = $cat->slug; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $loop = new WP_Query( array( 'post_type' => 'mypost_name', 'post-category' => $cname, 'posts_per_page' => 9, 'meta_key' => 'field2', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'paged'=>$paged ) ); while ( $loop->have_posts() ) : $loop->the_post();
Which sorts fine for one field.
Then Tried:
$cat = get_term_by('name', single_cat_title('',false), 'post-category'); $cname = $cat->slug; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $loop = new WP_Query( array( 'post_type' => 'mypost_name', 'post-category' => $cname, 'posts_per_page' => 9, 'meta_query' => array ( array ( 'key' => 'field2', ), array ( 'key' => 'field1', 'value' => 'valueA', 'compare' => 'LIKE' ) ), 'meta_key' => 'size', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'paged'=>$paged ) ); while ( $loop->have_posts() ) : $loop->the_post();
Which just limits the posts to ones with the field1/field2 value, and sorts them by field2.
Thanks for any help.
- The topic ‘OrderBy multiple meta_key ?’ is closed to new replies.