Skip Navigation

Cannot order results by distance in Views created with the Block editor

Open

Symptoms

With the legacy Views editor it is possible to set the order of results by distance from the location being searched.

The same option is missing from the settings in Views created with the Block editor.

The option would in principle work, but cannot be set.

We have an internal ticket about making this missing setting available.

Workaround

It is possible to modify the View settings on-the-fly as the View is being generated, using the wpv_view_settings filter.

Set up the View with location search and order by the address field, without specifying as a distance (the missing option).

Then add a code snippet at Toolset > Settings > Custom Code (this code does not need to run on the WP admin pages), with the following code:

add_filter( 'wpv_view_settings', 'ts_view_settings', 101, 2 );
function ts_view_settings( $view_settings, $view_id ){

    $address_field_slug = 'address'; // Edit 

    if ( $view_id == 35 ) // Edit View ID
    {
        $view_settings['orderby'] = "field-wpcf-$address_field_slug";
        $view_settings['orderby_as'] = 'DISTANCE';
        $view_settings['order'] = 'ASC';
        $view_settings['distance_order'] = array(
            'source'        => 'url_parameter',
            'center'        => '',
            'url_parameter' => 'toolset_maps_distance_center'
        );
    }

    return $view_settings;
}

You will need to edit the ID of the View as well as the slug of the address field.

Leave
a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>