X

Rearrange category order

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.

Solution:
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 ($latest) 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.

Code Snippet:

<?php
$categories = get_terms('books_category');

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

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

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!