I have a post type with an address.
I have a view showing posts of that type, and a filter in that View, that queries by location (distance from XY).
I want to add a default location when no query params are set (when no search is run by user) and I do NOT want to use current user location. I tried to use wpv_filter_query filter to:
- check if query is set
- if not, pass my own query args, effectively having a default query
PROBLEM:
wpv_filter_query does not even hold the "distance" search query args. No matter if I search by a location or distance, the wpv_filter_query never shows these values... so I cannot alter them either.
QUESTION:
How do we filter view query when searching by location? Is it even possible?
So the thing is, a Front End search by user location... is a query.
But yeah, I see it is not, thus, it is not possible to pass a default location only when there is no query run yet but only a always-present setting, which isn't the goal (since that would then overwrite all queries in the front end I would assume, being it a setting, rather than a query run by the user
It's weird the query is not part of wpv_filter_query, since it is a search run in the front end.
Thanks Minesh for the hint about looking in view_settings instead of wpv_filter_query.
Still I don't get it WHY it is like that but be it as it is.
The solution to run a View that has an initial distance to center set, and then lets you as well perform a search, looks as follows (considering a Post View but a USER field for the centring):
add_filter( 'wpv_view_settings', 'prefix_filter_distance_center_address', 10, 2 );
function prefix_filter_distance_center_address( $view_settings, $view_id ) {
/**
* We apply this to view ID 123456 and 7891011 in this case.
*/
if ( 123456 === (int) $view_id || 7891011 === (int) $view_id ) {
// Get user meta address.
$latlong = types_render_usermeta( 'user-geolocation', array( 'format' => 'FIELD_LATITUDE,FIELD_LONGITUDE', 'user_current' => true ) );
$lat = 0;
$lon = 0;
/**
* If the lat or long is empty, AND there is no search yet run
*/
if ( ! empty( $latlong )
&& empty ( $_GET )
) {
$latlon = explode( ',', $latlong );
$lat = $latlon[0];
$lon = $latlon[1];
$view_settings['map_distance_filter']['map_center_lat'] = $lat;
$view_settings['map_distance_filter']['map_center_lng'] = $lon;
}
}
return $view_settings;
}