Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Assume I have a bunch of posts (articles) in two categories: "upcoming events" (cat=1) and "past events" (cat=2). When listing all posts of a specific category out of those two, category 1 shoud be listed in ascending order (first posts first, i.e. earlier upcoming events first), while category 2 should be listed descendingly (earlier previous posts for past events should appear further down the list).

With menu entries for navigation, I can use URL parameters like

mywordpressblog.example/?cat=1&order=asc

However, since I have to add the second parameter "manually" it'll disappear when people just click on the category label that's shown for each post.

Hence, I need to pick a sort order when creating or modifying a category, so that this sort order be used when showing all posts of that category. Is there a way to do this?


Several related questions don't help me out - since their either asking for defining completely custom sort orders, for sorting categories (not posts), or because they're not yet solved or involve some twinkering the the code which I'd like to avoid in order for plugin and wordpress updates to work well. Setting Custom Sort Order of Posts within a Category http://wordpress.stackexchange.com/questions/22021/different-post-sort-order-within-different-categories Ascending sort order for monthly & category view, i.e. ?m=201204, ?cat=4

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

It's fairly simple to add it manually for your categories, If you want to be able to set and store the sort order from the admin UI, that's a bit more involved.

a manual fix can be achieved with a pre_get_posts hook:

function wpa55535_pre_get_posts( $query ){
    // if this is a category page
    if( $query->is_category ):
        // if cat = 1, set order to ASC
        if( $query->query_vars['cat'] == 1 ):
            $query->set( 'order', 'ASC' );
        // if cat = 2, set order to DESC
        elseif( $query->query_vars['cat'] == 2 ):
            $query->set( 'order', 'DESC' );
        endif;
    endif;
    return $query;
}
add_action( 'pre_get_posts', 'wpa55535_pre_get_posts' );

If you're using 'pretty' permalinks you'll have to check for category_name instead of cat, as it's queried by name not ID in that case.

share|improve this answer
    
Thanks for your quick reply. Looks very reasonable. I'll stick with the URL parameter added to self-made menu entries as it works for now, and wait for WP to offer that kind of choice when creating or modifying categories. –  Frank Jun 18 '12 at 9:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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