Posted on

Proximity sorting

Relevanssi Premium 2.16 adds proximity sorting to search results. That means you can sort the search results by geographic location. Instead of having the most relevant matches first, you can have the nearest results first.

There are many ways to use geolocation in WordPress. The way Relevanssi does this is flexible but requires some work. It is not complicated; you need to tell Relevanssi where to find the information it needs.

Relevanssi works with latitude and longitude values, and it needs the coordinates in the “61.4898, 23.7735” format, the most common format.

Setting up proximity sorting

First, you need to enable proximity sorting. As calculating the distances is an extra step, it’s not turned on by default. Add this to your theme functions.php to enable proximity sorting:

add_filter( 'relevanssi_proximity_sorting', '__return_true' );

The next step is to declare the comparison coordinates. Where is the spot against which Relevanssi compares the results? These coordinates can be a fixed spot or something the search user provides. Relevanssi looks for this in the coordinates query variable, and it should have the coordinates in the “latitude, longitude” format.

If this is not possible or easy, you can also provide the coordinates with a filter function. Add a filter function on the relevanssi_proximity_comparison filter hook. That function should return the coordinates as a string.

Then you need to provide the coordinates for each post. You give the location with the relevanssi_proximity_coordinates filter hook, which filters the coordinates and gets the post ID as the parameter.

Often the coordinates are in a custom field. The necessary function will look something like this:

	function( $coordinates, $post_id ) {
		return get_post_meta( $post_id, 'coordinates', true );

If you have posts that don’t have coordinates, Relevanssi assumes those posts are very far. They will be last on the sorting order. If you want them sorted first (or something else), you can set the default distance. Use the relevanssi_proximity_default_distance filter hook:

add_filter( 'relevanssi_proximity_default_distance', '__return_zero' ); // This would lift the uncoordinated posts first.

These are the steps you need to take to provide Relevanssi with the required information. Then you only need to set the orderby parameter to 'proximity' => 'asc'. This parameter will get you results in the ascending order of proximity:

add_filter( 'relevanssi_orderby', 'rlv_proximity_order' );
function rlv_proximity_order( $orderby ) {
  $orderby = array( 'proximity' => 'asc' );
  return $orderby;

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.