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 k开发者_Go百科now 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!
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!
in your archive.php, find the code
if (have_posts()) : while (have_posts()) : the_post();
and replace it with:
$cat_posts = new WP_Query($query_string."&orderby=title&order=ASC");
if ($cat_posts->have_posts()):while($cat_posts->have_posts()):$cat_posts->the_post();
this should do the trick.
update: this is taken if you want to change the source code.
well you can do 1 another thing in your archive.php
use this line of code
global $query_string; // required
$posts = query_posts($query_string."&orderby=title&order=ASC");
before this line of code
if (have_posts()) : while (have_posts()) : the_post();
you will get what you desire by the default wordpress loop. i hope this will help you much.
thank you all.
精彩评论