WordPress: Rearrange category order

on October 21st, 2011 in Tutorial, Wordpress

Just recently I ran into a problem with the category order. The oldest category was “New Publications”. So dividing the items based on their category and then looping over them would always put items from the “New Publications”-category at the end of the page, which is rather unpleasant. WordPress sadly has no option to rearrange the order of categories (at least I couldn’t find it).

Snippet

Here is the snippet that solves the problem:

$categories = get_terms('books_category');
      
for( $i=0; $i<sizeof($categories); $i++ ){
  if ( $categories[$i]->name == 'New Publications' ) :
    $latest = array($categories[$i]);
    unset($categories[$i]);
  endif;
}

if( isset($latest) )
  array_splice( $categories, 0, 0, $latest );

What it does

After querying for the categories (line 1) it loops through all categories until it (hopefully) finds the desired category. If the category was found it is saved into a new variable and removed from the category array (line 2-8). Line 11 inserts the category again at the beginning of the array. Now you can iterate through the categories and display your items and the new publications will always be the first displayed category.

Greetings,
Sebastian

Liked this? Share it!

Subscribe to the RSS Feed.

Comments

  1. Hans

    This problem sounds familiar ;) .
    Do you think there is any chance do add custom-fields in categories that allow you to order them? Could be a nice plugin, tho. Maybe there is one already.

    I would be interested in further thoughts :)

    October 26, 2011 – Reply

    • Sebastian

      Sure. Off the top of my head I would rather do it with a plugin so you can have a GUI to order you categories. It would work with custom fields you, too. But the sorting parameter has to be an integer or something alike. And inserting an category in the middle could be horrible for the user :D Also storing the final ordering of categories would help the performance, which is also cleaner with a plugin.

      October 26, 2011 – Reply

  2. Mike

    Or you can just use a drag and drop sortable interface <a href="http://wordpress.org/extend/plugins/taxonomy-terms-order/">Category Order and Taxonomy Terms Order</a> with no code update necessarily

    November 19, 2011 – Reply

  3. luis

    where can i add this code to rearrange the categories in the new post or edit post dashboard screen? Tankx

    May 30, 2012 – Reply

  4. Sebastian

    This snippet used when u develop WP Themes. You can not put it just it somewhere in AdminMenu :)

    June 5, 2012 – Reply

Leave a Comment