0

I have these two functions.

The difference is that one is filtering custom taxonomy (is_tax) and the other is filtering generic WordPress tags (is_tag).

The work as I'd like them to be it seems that the code is being duplicated.

This is Taxonomy:

add_action( 'pre_get_posts', 'sort_conference_by_date_tax' );
function sort_conference_by_date_tax( $query ) {
    if ( $query->is_main_query() && !is_admin() ) {
       if ( $query->is_tax() ) {
            $query->set('orderby', 'meta_value');  
            $query->set('meta_key', 'start_date');  
            $query->set('order', 'DESC'); 
       }       
    }
}

This is for Tags (Standard WordPress)

add_action( 'pre_get_posts', 'sort_conference_by_date_tag' );
function sort_conference_by_date_tag( $query ) {
    if ( $query->is_main_query() && !is_admin() ) {
       if ( $query->is_tag() ) {
            $query->set('orderby', 'meta_value');  
            $query->set('meta_key', 'start_date');  
            $query->set('order', 'DESC'); 
       }       
    }
}

I thought an array would work like this:

if ( $query->(array(('tag', 'tax'))) {
   return 0;
}

But it didn't seem to work for me...

I guess I am only doing something that would save a fraction of a second by merging these functions so if it can't be done prob best to just leave it alone right?

Thanks

  • 1
    This is essentially "How do I do an A or B check in PHP?" – Tom J Nowell May 13 at 1:00
1

Unless I'm missing something, I would think you could just use an OR (||) operator to check if it is_tag() or is_tax():

add_action( 'pre_get_posts', 'sort_conference_by_date' );
function sort_conference_by_date( $query ) {
    if ( $query->is_main_query() && !is_admin() ) {
       if ( $query->is_tag() || $query->is_tax() ) {
            $query->set('orderby', 'meta_value');  
            $query->set('meta_key', 'start_date');  
            $query->set('order', 'DESC'); 
       }       
    }
}
  • Thanks VERY much - works really well....if more than anything it just keeps it neat and tidy – henry May 13 at 1:29
  • Glad to hear that worked out! – butlerblog May 13 at 11:38

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.