-1

Is it possible to filter events (WP Query) within a Custom Taxonomy archive by ‘Start Dates’?

I create a Custom Post Type called “Events” and in that “Events” is a Start Date

When I view Custom Taxonomy listing data from the Custom Post Type I’d like for the events to be filtered by the Start Date in a DES manner.

I thought this code would work - am I on the right track?

//Using Wordpress Pre-Get filter to order the custom taxonomy by custom field
function customize_customtaxonomy_archive_display ( $query ) {
    if (($query->is_main_query()) && (is_tax('country')))

    $query->set( 'post_type', 'your-post-type' );  // not sure??               
    $query->set( 'posts_per_page', '-1' );
    $query->set( 'meta_key', 'start_date' ); // this is meta_field          
    $query->set( 'orderby', 'meta_value_num' );
    $query->set( 'order', 'ASC' );
}

 add_action( 'pre_get_posts', 'customize_customtaxonomy_archive_display' );

The above comes from here: Custom Taxonomy order by Custom Field

I thought the above would work for me but it didn't - perhaps because I wasn't sure what to add in the $query->set( 'post_type', 'your-post-type' ); bit

What should I be adding there?

  • 'your-post-type' will be your "Events" type slug, probably 'event'. – nmr May 11 at 6:53
0

Nothing. You shouldn't need to set the post type. Your taxonomy archive is presumably already querying the correct post type.

function customize_customtaxonomy_archive_display ( $query ) {
    if ( $query->is_tax( 'country' ) ) {
        $query->set( 'meta_key', 'start_date' );
        $query->set( 'orderby', 'meta_value_num' );
        $query->set( 'order', 'ASC' );
    }
}

Note:

  • $query->is_main_query() is redundant when checking $query->is_tax(), because (as far as I'm aware) secondary queries can never be a taxonomy archive.
  • Setting the posts per page has nothing to do with sorting, so I've omitted it.
  • You need to use {} with if statements, otherwise the condition will only apply to the next line. The original code you've copied will apply that sorting and posts per page value to all queries. Even if you only have one line, omitting the brackets is considered poor practice.
  • Thanks Jacob - ok - so how can I sort a custom taxonomy by a ‘start date’? The ‘start date’ is from a custom post type. Is there any resource or suggestion of how I can do this? – henry May 11 at 6:54
  • Sorry, I don't understand. That's in my answer (and your original question). You were asking about the post_type property. If this isn't working, then the solution depends on how you're storing the date. – Jacob Peattie May 11 at 6:56
  • Ok got it - thanks - am reading this on the road - pardon brevity – henry May 11 at 7:19

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.