How to change the order of posts in the WordPress loop

This is not rocket science but it took me a while to find the answer, so here it is.

Situation: On some WordPress archive pages you’d like to order the posts by title rather than the default date order.

The following function will do just that, it will merge the WordPress loop query with two new parameters ‘orderby’ and ‘order’ – leaving the rest of the query as is.

Here I’ve hooked it to a thesis hook, but you can hook it anywhere as long as its before your loop starts.

The other part of this is the conditional statement. In this example I’ve got is_tax(‘buscategory’), relevant for a particular job, but you can use any WordPress conditional tags.

function change_post_order(){
		if (is_tax( 'buscategory' ) || is_search()){
			global $wp_query;
			$args = array_merge( $wp_query->query, array( 'orderby' => 'title','order' => 'ASC' ) );
			query_posts( $args );
	}
}
add_action('thesis_hook_before_content','change_post_order');

Here’s another example that would work if you’re using the Genesis Theme Framework from StudioPress. This example will re-order the posts by their title, if they are in Category 9

function dma_change_post_order(){
        if ( is_archive('9') ){
            global $wp_query;
            $args = array_merge( $wp_query->query, array( 'orderby' => 'title','order' => 'ASC' ) );
            query_posts( $args );
    }
}
add_action('genesis_before_loop','dma_change_post_order');

Comments

  1. Thanks for the info… which file do you add this to on the wordpress site?

    • Rich, depends on which theme / framework you’re using but as a general rule this kind of thing can go in the functions.php file.

Speak Your Mind

*