wordpress query with custom fields help

My posts have a bunch of custom fields and are currently being ordered by “over-lenght”

I have another custom field called “over-lenghtin”.

Read More

I’d like to continue to order my posts by over-lenght but if 2 posts had the same value for this field I’d like to also order them by over-lengthin.

I’m wondering how I can modify my query or add a function to execute this?

Here’s by current query

$loop = new WP_Query( array ( 'post_type' => 'new', 'orderby' => 'meta_value_num', 'meta_key' => 'over-length', 'meta_query' => array( array( 'key' => 'over-make', 'value' => 'Doral', 'compare' => 'LIKE') ) ) );

Ok so I’ve rewritten by query to use $wpdb->get_results, but I’m still a bit confused on how to go about ordering by 2 different custom fields.

Here’s my new query:

$wpdb->get_results("SELECT * FROM $wpdb->posts, wp_postmeta  WHERE wp_posts.ID = wp_postmeta.post_id AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'new' AND wp_postmeta.meta_value = 'Doral' ORDER BY");

Now I need to order by my custom fields ‘over-length’ and then ‘over-lengthin’

I seem to have this working now, here’s my final query:

$wpdb->get_results("SELECT * FROM $wpdb->posts 
LEFT JOIN $wpdb->postmeta AS overlength ON(
$wpdb->posts.ID = overlength.post_id
AND overlength.meta_key = 'over-length'  
)
LEFT JOIN $wpdb->postmeta AS overlengthin ON(
$wpdb->posts.ID = overlengthin.post_id
AND overlengthin.meta_key = 'over-lengthin'  
)
LEFT JOIN $wpdb->postmeta AS overmake ON(
$wpdb->posts.ID = overmake.post_id
AND overmake.meta_key = 'over-make'  
)
WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'new' AND overmake.meta_value = 'Doral' ORDER BY 0+overlength.meta_value DESC, 0+overlengthin.meta_value  DESC");

Related posts

Leave a Reply

1 comment