Add filter post_where and passing post_type argument

Following this tutorial, I want to search for posts within the radius where the post_type=profile

add_filter('posts_where', 'location_posts_where', 10);
$query = new WP_Query( array( 'post_type' => 'profile' ) );  
remove_filter('posts_where', 'location_posts_where', 10);


function location_posts_where( $where )  
{  
    global $wpdb;  

    $latitude = filter_input( INPUT_GET, "latitude", FILTER_SANITIZE_STRING );
    $longitude = filter_input( INPUT_GET, "longitude", FILTER_SANITIZE_STRING );

    // Specify the co-ordinates that will form  
    // the centre of our search  
    //$latitude = '-27.922459';  
    //$longitude = '153.334793'; 

    $radius = '125'; // (in miles)  

   if (is_search() && get_search_query())
    // Append our radius calculation to the WHERE  
    $where .= " AND $wpdb->posts.ID IN (SELECT post_id FROM lat_lng_post WHERE 
         ( 3959 * acos( cos( radians(" . $latitude . ") ) 
                        * cos( radians( lat ) ) 
                        * cos( radians( lng ) 
                        - radians(" . $longitude . ") ) 
                        + sin( radians(" . $latitude . ") ) 
                        * sin( radians( lat ) ) ) ) <= " . $radius . ")";  


    // Return the updated WHERE part of the query  
    return $where;  
}    

But it displays no posts and when I debug, this is the SQL query it is actually running:

SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) AND wp_posts.ID IN (SELECT post_id FROM lat_lng_post WHERE 
( 3959 * acos( cos( radians(-27.922459) ) 
* cos( radians( lat ) ) 
* cos( radians( lng ) 
- radians(153.334793) ) 
+ sin( radians(-27.922459) ) 
* sin( radians( lat ) ) ) ) <= 125) ORDER BY wp_posts.post_date DESC LIMIT 0, 5

This line is the problem: AND wp_posts.post_type = 'post' Why isn’t the WP_Query argument working to pass post_type = profile? Or am I doing something wrong?

Solutions Collecting From Web of "Add filter post_where and passing post_type argument"

Remove this part from your posts_where filter:

if (is_search() && get_search_query())

Note that is_search() is a check on the main query.

If you want to target the main search query, there’s the posts_search filter available.

Important: Watch out for possible SQL injections, as you are taking user input into the SQL query. I think the FILTER_SANITIZE_STRING filter is too weak here, as it allows e.g. parentheses, where it allows the user to modify the structure of the SQL query. Consider $wpdb->prepare() with %for %F type specifiers for floating point numbers.

You are removing the filter too early. Remove it after you have completed your loop and everything should be fine. Simply building a new WP_Query object doesn’t actually apply the filters on instantiation. The filters are applied in the get_posts() method of the query object.