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


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 Different post sort order within different categories Ascending sort order for monthly & category view, i.e. ?m=201204, ?cat=4

1 Answer 1


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' );
    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.

  • 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
    Commented Jun 18, 2012 at 9:02

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.