I have a custom search query which I have put in a plugin. The homepage has a custom search form and when the user searches for something, it goes to the search page and displays the result.
My issue is that the custom query runs on every page of the website, even in the admin panel. It keeps throwing the error latitude and longitude not defined
on every page.
I have used is_search()
function to make sure the function runs only on search pages but it doesn't work. It still runs the query!
This is the code:
/**
* Custom Search on Homepage
*
*
*/
add_filter('posts_fields', 'distance_query');
add_filter('posts_where', 'lat_lng_define');
add_filter('posts_join', 'lat_lng_join');
add_filter('posts_groupby', 'having_distance');
add_filter('posts_orderby', 'sort_distance');
/**
* The Fields
*
*
*/
function distance_query( $fields ) {
global $wpdb;
//if(isset($_GET['latitude'] )|| isset($_GET['longitude'] )) {
$lat = sanitize_text_field( $_GET['latitude'] );
$lng = sanitize_text_field( $_GET['longitude'] );
//} else {
// return;
//}
if (is_search())
$fields .= ",
SOME QUERY"
return $fields;
}
/**
* The Join
*
*
*/
function lat_lng_join( $join) {
global $wpdb;
if (is_search())
$join = " QUERY";
return $join;
}
//Likewise the rest of the query
If I isset the $GET values, the homepage shows 404:
if(isset($_GET['latitude'] )|| isset($_GET['longitude'] )) {
$lat = sanitize_text_field( $_GET['latitude'] );
$lng = sanitize_text_field( $_GET['longitude'] );
} else {
return;
}
The search query running on every page is making my website too slow. Any assistance would be appreciated.
$lat
and$lng
within theis_search()
conditional?{}
so the query is modified regardless of the if statement. If this is not a copy/paste error, try to putif( is_search() ) { $fields = ...; return $fields }
same thing with your$join
variable.if
without the{}
will consider ONLY the next statement as part of the condition.