You are here:  » Sorting order of filter


Sorting order of filter

Submitted by marco@flapper on Fri, 2016-09-23 10:26 in

I have Size as an optional field and filter and I noticed the sorting is alphabetical.

So I have sizes for example in this order: 10 years, 104, 42, S, M, L, XL, XS etc.

I would like a sorting order like: 10 years, 42, 104, S, M, L, XL, XS

Or maybe even better: XS, S, M, L, XL, 42, 104, 10 years. But I guess this would be very complicated also maintaining it.

How could this be done?

Submitted by support on Fri, 2016-09-23 10:52

Hi Marco,

PHP's usort() function is handy for this kind of scenario. A look-up table can be created with a weighting value for each size and then used in a usort callback function.

In the modified pto_search.php that you are using to show filters for custom fields, look for the following code at line 865:

  function pto_search_filters_html()

...and REPLACE with:

  $pto_sizeWeighting = array("XS"=>0,"S"=>1,"M"=>2,"L"=>3,"XL"=>4,"42"=>5,"104"=>6,"10 years"=>7);
  function pto_cmpSize($a, $b)
  {
    global $pto_sizeWeighting;
    if (!isset($pto_sizeWeighting[$a->size])) $pto_sizeWeighting[$a->size] = 999;
    if (!isset($pto_sizeWeighting[$b->size])) $pto_sizeWeighting[$b->size] = 999;
    if ($pto_sizeWeighting[$a->size] == $pto_sizeWeighting[$b->size])
    {
      return 0;
    }
    return ($pto_sizeWeighting[$a->size] < $pto_sizeWeighting[$b->size]) ? -1 : 1;
  }
  function pto_search_filters_html()

And then the following code at line 977:

      $html_filter = "";

...and REPLACE with:

      if ($filter == "size")
      {
        usort($wpdb->last_result,"pto_cmpSize");
      }
      $html_filter = "";

Any values not in the $pto_sizeWeighting array will sort with a weighting of 999 so will be pushed to the of the selection...

Hope this helps!

Cheers,
David.
--
PriceTapestry.com