Order Posts by Closest Numeric Values

One possibility is a direct SQL query similar to the one given here.

But I’m not convinced that it would be much more efficient than 2 queries, all handled by WordPress:

The is untested

$price =0; //Price of current property
$id=0; //Property (post) ID.

$args = array(
    'post_type' => 'property',
    'post__not_in'=>array($id),
    'posts_per_page'=> 2,
    'meta_query' => array(array(
        'key' => 'price',
        'value' => $price,
        'type' => 'numeric',
        'compare' => '>='
        )),
     'meta_key'=> 'price',
     'orderby'=>'meta_value_num',
     'order'=>'ASC'
    );

 $two_above = get_posts($args);

 //Put their IDs along with current property ID in an array
 $ids = array_values(wp_list_pluck($two_above, 'ID'));
 array_push($ids, $id);

 //Exclude returned properties and current property from next query
 $args['post__not_in'] = $ids;

 $args['meta_query']['compare'] = '<=';
 $args['order'] = 'DESC';

 $two_below = get_posts($args);

Leave a Comment