Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order categories in WordPress?

I use wp_list_categories() to get the list of all the categories and generate the navigation bar. Is there a way to order these categories in a particular order other than alphabetical ordering.

eg: Connect, News & Views, Q&A, Hello Startup, Startup 101...

like image 716
Saneef Avatar asked Feb 05 '09 21:02

Saneef


2 Answers

Most themes don't use the description of the category for anything. Easy workaround I did was to use numbers in description. The top post here currently has some jQuery hack from here, it's unneeded.

You can add custom order fields I suppose as well.

Just

$categories = get_categories( array(
    'orderby' => 'description',
    'order'   => 'ASC'
) );
like image 66
Chasevanb Avatar answered Sep 25 '22 09:09

Chasevanb


Technical approach

The problem in wordpress core is that the table wp_terms has no term_order column. That means, standard wordpress does not support the custom term order. If you look at this WP database structure you can find the table wp_term_relationships. This table is responsible for the relationships between posts and the taxonomy (your categories) AND this table has a term_order column.

Now, with a simple SQL statement ALTER TABLE wp_terms ADD term_order INT(11) NOT NULL DEFAULT 0 (not forget the $wpdb->wp_terms variable) you can add a column to the table, which is responsible for your custom category order. Then you can put your custom category order in this two columns of wp_term_relationships and wp_terms. When all is finished, you can hook into the filter of get_terms_args and change the orderby to term_order.

Here a list of all relevant links for the technical approach:

  • https://codex.wordpress.org/Database_Description for the wp database structure
  • https://codex.wordpress.org/Class_Reference/wpdb for the $wpdb->wp_terms
  • https://developer.wordpress.org/reference/hooks/get_terms_args/ for the WP filter

A plugin can do the job for you

Check my plugin to solve this: WordPress Real Categories Management. WP RCM creates an extra field term_order on the wp terms table. It also brings a lot of other useful features as you can see in the screenshot below. It allows you to organize your wordpress categories in a nice way. It is easy to use, just drag&drop your categories and move it to a specific order. The plugin works in all Custom post types.

Drag & Drop categories order

From the product description i can quote. If you want to try the plugin, there is also a demo on the plugin page.

There are a lot of free plugins

This can be solved with a lot of free plugins available within the wordpress.org plugin repository. Simply search for "category order" in your Wordpress Dashboard > Plugins > Install.

like image 26
Matthias Günter Avatar answered Sep 21 '22 09:09

Matthias Günter