Sorting FacetWP Dropdown/Radio Facet Values Numerically
When using FacetWP, a WordPress filtering plugin, you may need to sort facet values numerically instead of alphabetically, especially for numeric values like ages or grades. By default, FacetWP sorts values as strings, leading to incorrect ordering (e.g., 10 before 2).
The following code snippet sorts specific facets numerically using the facetwp_facet_orderby filter:
add_filter('facetwp_facet_orderby', function ($orderby, $facet) {
if (in_array(
$facet['name'],
[ 'program_minimum_age', 'program_maximum_age', 'program_minimum_grade', 'program_maximum_grade', 'program_minimum_hours', 'program_maximum_hours' ],
true
)) {
$orderby = 'CAST(facet_value AS UNSIGNED) ASC';
}
return $orderby;
}, 10, 2);
How It Works
Filter Hook:
The facetwp_facet_orderby filter is triggered before FacetWP executes the SQL query for facet ordering.
Facet Check:
The code verifies if the facet’s name is among the numeric facets (e.g., program_minimum_age).
Numeric Casting:
Using CAST(facet_value AS UNSIGNED) ensures values are treated as numbers in SQL, yielding the correct ascending order.
Return Statement:
The $orderby variable is updated only for these facets, leaving others unchanged.
Why This Matters
Without this adjustment, facet values like 1, 10, 2, 3 may be sorted alphabetically as 1, 10, 2, 3 instead of the correct numeric order 1, 2, 3, 10, enhancing user experience and ensuring logical filtering.