Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active August 29, 2015 13:57
Show Gist options
  • Save tommcfarlin/7c36a62b36c7debd0de6 to your computer and use it in GitHub Desktop.
Save tommcfarlin/7c36a62b36c7debd0de6 to your computer and use it in GitHub Desktop.
[WordPress] A strategy for naturally ordering a small collection of taxonomy terms.
<?php
/**
* An example for how to query for custom taxonomies and then naturally
* order their terms.
*
* The example used here is in the context of a book that has chapters
* such as:
*
* - Chapter 1
* - Chapter 2
* - ...
* - Chapter 10
* - Chapter 11
*
* Originally published March 7, 2014
* http://tommcfarlin.com/wordpress-terms-in-alphabetical-order/
*/
// Grab the terms for the current taxonomy
$book_term = get_term_by( 'name', $book_name, 'tax_book' );
// Now grab the chapters for the current book
$chapter_ids = get_term_children( $book_term->term_id, 'tax_book' );
// Iterate through the chapter IDs and add the full term to an array
$chapters = array();
for ( $i = 0, $l < count( $chapter_ids ); $i < $l; $i++ ) {
array_push( $chapters, get_term_by( 'id', $chapter_ids[ $i], 'tax_book' ) );
} // end for
// Create an associative array of the chapters using their term ID and chapter name
$organized_chapters = array();
foreach ( $chapters as $chapter ) {
$organized_chapters[ $chapter->term_id ] = $chapter->name;
}
// Now sort the chapters in natural order
natsort( $organized_chapters );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment