Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change default wordpress query to orderby title

I would like to change the wordpress default query to orderby title when viewing a category, rather than the post id.

For reasons too boring to explain(!) I would like to change the default setting rather than use a custom query (which I know how to do)

Ideally it would be some code that goes in the functions.php of my template, rather than having to hack the core installation.

Thanks for your help people!

like image 324
JorgeLuisBorges Avatar asked Nov 27 '22 22:11

JorgeLuisBorges


1 Answers

You can also use the action 'pre_get_posts' to change the orderby and order variables like this:

add_action( 'pre_get_posts', 'custom_get_posts' );

function custom_get_posts( $query ) {

  if( (is_category() || is_archive()) && $query->is_main_query() ) {    
    $query->query_vars['orderby'] = 'name';
    $query->query_vars['order'] = 'ASC';
  }

}

Note: the is_main_query() check helps make sure you don't cause unintended behaviors in plugins and theme functionality. Removing it is OK but make sure you know what else you are affecting!

like image 194
Jeremy Ferguson Avatar answered Dec 24 '22 00:12

Jeremy Ferguson