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!
Use a switch statement and combine your matching cases.
Hope that helps.
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 🙂Or other examples you can see it here: http://devotepress.com/wordpress-coding/when-to-use-pre_get_posts-in-wordpress/
Double pipes
||
save the day!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!