Wordpress sort by distance and featured post query

admin

Administrator
Staff member
I am trying a mysql query to sorts posts via distance lets say within radius 250 miles , everything works fine except that I need to order posts in a way that featured posts are always at top .
Here is my mysql query (I am doing it on wordpress).

Code:
    SELECT SQL_CALC_FOUND_ROWS wp_posts.*, ( 3959 * acos( cos( radians(40.140711) ) * cos(      radians( latitude.meta_value ) ) * cos( radians( longitude.meta_value ) - radians(-74.20619299999998) ) + sin( radians(40.140711) ) * sin( radians( latitude.meta_value ) ) ) ) AS distance , 
latitude.meta_value AS latitude , 
longitude.meta_value AS longitude
    FROM wp_posts 
    INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) 
    INNER JOIN wp_postmeta AS latitude ON wp_posts.ID = latitude.post_id 
    INNER JOIN wp_postmeta AS longitude ON wp_posts.ID = longitude.post_id 
    WHERE 1=1 
    AND wp_posts.post_type = 'event' 
    AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'recurring') 
    AND (wp_postmeta.meta_key = 'st_date' ) 
    AND latitude.meta_key="geo_latitude" 
    AND longitude.meta_key="geo_longitude" 
    AND wp_posts.ID in (SELECT tr.object_id FROM wp_term_relationships tr JOIN wp_term_taxonomy t on t.term_taxonomy_id=tr.term_taxonomy_id WHERE t.term_id IN ('3','4','5','6','7','8','9','10')) 
    AND (wp_posts.ID IN (SELECT wp_postmeta.post_id FROM wp_postmeta WHERE wp_postmeta.meta_key='st_date' 
    AND date_format(wp_postmeta.meta_value,'%Y-%m-%d') >'2013-09-23 14:35:58')) 
    GROUP BY wp_posts.ID HAVING distance <= 250 
    ORDER BY (SELECT wp_postmeta.meta_value FROM wp_postmeta, wp_posts AS p where wp_postmeta.post_id=p.ID AND wp_postmeta.meta_key = 'featured_h') ASC, distance ASC LIMIT 0, 10

The issue is with ORDER BY , it gives me error " Subquery returns more than 1 row"

IF I remove ORDER BY (select wp_postmeta.meta_value from wp_postmeta, wp_posts as p where wp_postmeta.post_id=p.ID and wp_postmeta.meta_key = 'featured_h'

it works fine but then it don't shows fetaured posts on top ,any way to fix it.