2

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.

2

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:

  • Thanks for this, so where would I put my query options (orderby, etc.)? in the $query->set( 'tax_query', array() );? – Dean Elliott Aug 3 '14 at 16:42
  • Yes, just have a look at the available WP_Query methods. I'll update my answer in a minute. – tfrommen Aug 3 '14 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.