Question

Basically I'm working on a website for a USB Drive manufacturer. I've used a custom taxonomy to represent the memory sizes for each USB drive this company offers. Here's how WordPress outputs my terms...

$terms = get_the_terms($post->ID, 'usb_mem');

if ($terms) {
 foreach ($terms as $taxindex => $taxitem) {

     echo '<span class="product_terms">' . $taxitem->name . '</span>';

 }
}

-16GB
-1GB
-256MB
-2GB
-32GB
-4GB
-512MB
-8GB

I need WordPress to sort them by actual data size, not just numerically. Ideally something like this:

-256MB
-512MB
-1GB
-2GB
-4GB
-8GB
-16GB
-32GB

Thanks in advance! :D

Was it helpful?

Solution

Note that all of this code is inline. You're better off:

  • Normalizing the size on import, which obviates most of this mess.
  • Constructing a class to handle all of this.

Any which way, here is the appropriate code.

// This is our lookup table to deal with strings.
$size_lookups = array('GB'=>pow(2,30), 'MB'=>pow(2,20), 'KB'=>pow(2,10), 'TB'=>pow(2,40));

// First, normalize all of the fields.
foreach ($terms as $taxitem)
{
   $taxitem->fixed_size = intval($taxitem->size,10);
   foreach ($size_lookups as $sizekey=>$sizemod)
   {
      if (strripos($taxitem->size, $sizekey))
      {
          $taxitem->fixed_size = intval($taxitem->size, 10) * $sizemod;
          break;
      }
   }
}

// Set up a sorting function.
function sortBySize($a, $b)
{
    return $b->fixed_size - $a->fixed_size;
}

// Do the sort.
$sorted = array_values($terms); // set up a shadow copy with new indexes.
usort ($sorted , 'sortBySize' );

// Display the results.
foreach ($sorted as $taxitem) {
    echo '<span class="product_terms">' . $taxitem->name . '</span>';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top