How to Sort Query Results By Meta Key/Value?
-
I am developing a business directory site and have created a simple “sort by” dropdown using the <select> tag for the frontend so users can display search results based on title, date, etc.
I want to add the ability to sort by “highest rated” to return the businesses which have the best ratings first. I have the rating system all setup but I have been unable to add this to my sort dropdown by meta key/value.
The meta key is “rating_avg” and the meta value is “comment_count” so I have tried the following php (bold text):
.... } } elseif ( $orderby_value == 'post_title' ) { $clauses['orderby'] = $wpdb->prefix.'posts.post_title'; } elseif ( $orderby_value == 'post_date' ) { $clauses['orderby'] = $wpdb->prefix.'posts.post_date'; } elseif ( $orderby_value == 'post_id' ) { $clauses['orderby'] = $wpdb->prefix.'posts.ID'; } elseif ( $orderby_value == 'random' ) { $clauses['orderby'] = 'RAND()'; } elseif ( $orderby_value == 'most_ratings' ) { $clauses['orderby'] = $wpdb->prefix.'posts.comment_count DESC'; } <strong>elseif ( $orderby_value == 'highest_rating' ) { $meta['key'] = 'rating_avg'; $clauses['orderby'] = $wpdb->prefix.'posts.comment_count DESC';</strong> } //return modified clauses return $clauses; }
I have tried a lot of different methods but cannot figure this out. The “Comment Count” works fine, but using the same structure as above how can I identify the meta key/value of the average ratings so I can use it in the dropdown?
Thanks!
- The topic ‘How to Sort Query Results By Meta Key/Value?’ is closed to new replies.