Can I restrict members by location

Hi I am about to create a directory. Using GeoLocation, would it be possible to restrict members based on location?

We were thinking of allowing them to advertise in three locations (for example Essex, London and Suffolk) and only view listings, make postings in these areas only.

Please does a human being know the answer/workaround?

HivePress Ai says yes, but that little devil has caught me out in the past.

Hi,

Unfortunately, there’s no such option in the Google or Mapbox API. For example, Google allows restricting results by country, but not by administrative area. This means that implementing this would require custom validation logic.

A possible (and probably the simplest) workaround would be to prevent users from adding listings whose address does not contain one of the regions you mentioned.

This way, you wouldn’t need to manually check every new listing, and users wouldn’t be able to add listings without one of the required regions in their location field.

The downside is that this does not technically restrict the search itself. However, since there would be no listings from other regions, searches for those regions would simply return no results. You could also clearly indicate on the website that it is intended for the mentioned regions.

Please try the sample code snippet below:

add_filter( 'hivepress/v1/models/listing/errors', function ( $errors, $listing ) {
	$allowed_regions = [ 'Essex', 'London', 'Suffolk' ];

	$location = $listing->get_location();
	$match    = false;

	foreach ( $allowed_regions as $region ) {
		if ( stripos( $location, $region ) !== false ) {
			$match = true;
			break;
		}
	}

	if ( $location && ! $match ) {
		$errors[] = esc_html__( 'Sorry, listings are currently only accepted in Essex, London or Suffolk.', 'hivepress' );
	}

	return $errors;
}, 10, 2 );

This should prevent users from adding listings if their address does not contain “Essex,” “London,” or “Suffolk”.

Hope this helps