1

I have a taxonomy template that is returning the correct posts (actually a custom post type) but I want to alter the order in which the posts are displayed. However, nothing I've tried will change the order of the posts from chronological. I've assumed that since the posts have already been returned then I should use 'query_posts' to alter the order of the posts. Accordingly, based on the codex, I added the following before the loop on the template:

<?php 
global $query_string;
query_posts( $query_string . '&order=>ASC');
?>

Changing "ASC" to "DESC" produces no changes in the listing.

NOTE: The end result I want will be more complicated than this example but for the moment I can't even get a simple sort like above to work.

I've also tried using this approach

<?php $sectionarg = array(
                     'order' => 'ASC',
                        );
query_posts($sectionarg);       ?>      

But that completely destroys the original list of returned posts and replaces it with regular posts. So it appears that to maintain the original query you have to use the first approach but how then do you sort the returned posts? Any advice would be greatly appreciated. Thanks

1 Answer 1

1

I've assumed that since the posts have already been returned then I should use 'query_posts' to alter the order of the posts.

That assumption is wrong. You should pretty much never use query_posts.

Use a filter on pre_get_posts.

function pregp_wpse_108235( $qry ) {
    if ( $qry->is_main_query() && $qry->is_tax() ) {
        $qry->set( 'order', 'ASC' );
    }
}
add_action( 'pre_get_posts', 'pregp_wpse_108235' );

But that completely destroys the original list of returned posts and replaces it with regular posts.

Yes, what you did would return the normal post index. You did not supply any of the taxonomy arguments, but as query_posts is the wrong way to go anyway there is no point in worrying about that.

1
  • Thanks - worked perfectly. Very helpful answer. For any other neophytes like me you can use this code almost verbatim but you need to get the names matching.
    – dorich
    Commented Jul 29, 2013 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.