Thread Starter
skarck
(@skarck)
to simplify the question:
how can i override a query with a newly set up WP_Query (or in my case WP_GeoQuery) in pre_get_posts filter?
this is not working:
function my_places_modify_query( $query ) {
global $query;
if ( 'places' === $query->query_vars( 'post_type' )
&& $query->is_archive() ) {
$query = new WP_Query( array( [do stuff...] ) );
}
return $query;
}
add_filter( "pre_get_posts", "my_places_modify_query" );
thanks in advance!
pre_get_posts is an action, not a filter, so use add_action()!
FWIW, as an action, a value returned by your function will be ignored. You also don’t need to globalize $query, as it’s passed by reference.
You goal here should be to alter the current archive query, not create a new one. Otherwise, you may as well just use query_posts(). So use the $query object’s set method to set specific query variables inside of your if places && archive block. As in:
$query->set('meta_key', 'my_meta');
$query->set('meta_value', 'my_value');
In general the way to use pre_get_posts would look like:
function my_places_modify_query( $query ) {
if ( is_post_type_archive('places') && is_main_query() ) {
set_query_var( 'orderby', 'meta_value_num' );
set_query_var( 'meta_key', 'search_longitude' ); //where search_longitude is a post meta field
}
}
add_action( "pre_get_posts", "my_places_modify_query" );
However, I don’t believe you this will work for you since as far as I know, you can’t use pre_get_posts to sort by 2 meta values… for that you will need a custom query.
I think you might need to filter posts_join and then posts_orderby.. or possibly posts_where. And I’m not sure how to do this in the context of using the haversine formula to calculate distance between the different coorderinates. I think you’d need posts_where if you wanted to limit distance by X miles (or kilometers for the rest of the world) . This is a tricky one.
As an example: I just wrote this code to sort by author name and then meta value:
http://wordpress.stackexchange.com/questions/66507/how-to-sort-custom-post-type-posts-in-default-order-by-multiple-fields#answer-66614
It might serve as a basic example of posts_join.
Can you post your code that registers the query vars?
Also, have you seen the GEO my WP plugin?
Using Google’s API tools GEO my WP provides an advance proximity search for any post type or buddypress’s members based on a given address.