How to create a custom sort for WordPress categories

If you’re already using Advanced Custom Fields (which you should be!) you can create an order field for your categories from which you can set them manually in numerical order.

Then all you have to do is:

$categories = get_categories( $args );  

usort($categories, function($a, $b) {
   return get_field("category_order", "category_".$a->term_id) - get_field("category_order", "category_".$b->term_id);
});

foreach ($categories as $category){
...

Where category_order is the field name you created with ACF.

Note: Using the PHP 5.3 way of usort.

Leave a Comment