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:
if ( $post_type == 'games' OR 'consoles') OR {
$wp_query->set('orderby', 'title');
$wp_query->set('order', 'ASC');
}
Thanks!
4 Answers
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.