How to choose a sort order (for posts) per category? (ideally when creating a new category)

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.

Leave a Comment