Is there a way that I can modify the main loop in a single taxonomy template, but leave it untouched in every other template?
In this case, I have a custom post type called “Events” which in turn has a custom taxonomy called “Region”. What I want to do is, instead of listing each custom “Events” post chronologically by post date I want to order it by a custom meta value (In this case event_date
).
I only want to do this in my taxonomy-region.php
template and leave any other instance of the main loop untouched.
1 Answer
You could hijack the $query
just before fetching the posts.
function wpdev_156674_pre_get_posts( $query ) {
if (
$query->is_main_query()
&& $query->is_tax( 'region' )
) {
// Manipulate $query here, for instance like so
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'meta_key', 'event_date' );
$query->set( 'order', 'DESC' );
}
}
add_action( 'pre_get_posts', 'wpdev_156674_pre_get_posts' );
References:
pre_get_posts
action hookWP_Query
class