If post_type is This or This

I’m basically using this bit of code in my functions.php to order my custom post types by title in ascending order.

function set_custom_post_types_admin_order($wp_query) {
  if (is_admin()) {

    $post_type = $wp_query->query['post_type'];

    if ( $post_type == 'games') {
      $wp_query->set('orderby', 'title');
      $wp_query->set('order', 'ASC');
    }
    if ( $post_type == 'consoles') {
      $wp_query->set('orderby', 'title');
      $wp_query->set('order', 'ASC');
    }
  }
}
add_filter('pre_get_posts', 'set_custom_post_types_admin_order');

Is there a way to combine those twoif statements, so I’m not repeating code. Something like this:

Read More
if ( $post_type == 'games' OR 'consoles') OR {
      $wp_query->set('orderby', 'title');
      $wp_query->set('order', 'ASC');
}

Thanks!

Related posts

4 comments

  1. Use a switch statement and combine your matching cases.

    function set_custom_post_types_admin_order( $query ) {
    
        // If not admin or main query, bail.
        if( !is_admin() || !$query->is_main_query() ) 
            return;
    
        $post_type = $query->query['post_type'];
    
        switch( $post_type ) {
            case 'games':
            case 'consoles':
            //case 'other_example_match':
                $query->set('orderby', 'title');
                $query->set('order', 'ASC');
            break;
            default:
                return;
        }
    }
    add_action( 'pre_get_posts', 'set_custom_post_types_admin_order' );
    

    Hope that helps.

  2. Firstly, you’ll want to be real careful when attaching to the pre_get_posts hook. This fires on every single query that gets run throughout your site. I would strongly advise you add another condition or two to the start of your function to limit the scope of this filter.

    Secondly, I would suggest checking if ( in_array( $post_type, array( 'games', 'consoles' ) ) as a better alternative for your condition.

    The way you’re using the OR statement here is actually incorrect, and you’ll need to expand out the condition better, e.g. if ( $post_type == 'games' || $post_type == 'consoles' ). If you choose to stick with this way of writing the condition, I would also suggest adopting the habit of writing “yoda conditions”, like so: if ( 'games' == $post_type || 'consoles' == $post_type ).

    In a “yoda condition”, the value is followed by the variable, making it much easier to spot a missing = symbol and an errant statement. Your life will be much happier this way, trust me 🙂

  3. Double pipes || save the day!

    if ( $post_type == 'games' || $post_type == 'consoles') {
          $wp_query->set('orderby', 'title');
          $wp_query->set('order', 'ASC');
    }
    

    This does exactly what I set out to do!

    Edit:
    or also works in place of the double pipe. You learn something new every day!

Comments are closed.