facetwp_facet_orderby
Overview
This filter lets you control the display order of values within a facet.
How it Works
FacetWP uses the facetwp_index
table to store facet values. When loading values for a facet, the SQL query looks like the following:
SELECT * FROM wp_facetwp_index f WHERE {where} ORDER BY {orderby};
This filter lets you customize the {orderby}
above. You have access to the table columns (facet_value, facet_display_value, term_id, etc.), but not menu_order
. If you need to sort by arbitrary values, see the example below.
Parameters
- $orderby | string | The original “ORDER BY”
- $facet | array | An array of facet properties (see below)
$facet = [ 'name' => 'my_facet', 'type' => 'checkboxes', 'source' => 'tax/category', ... ];
Sort numerically
The following example sorts a facet named “year” numerically
add_filter( 'facetwp_facet_orderby', function( $orderby, $facet ) { if ( 'year' == $facet['name'] ) { // Change "year" to your facet's name $orderby = 'f.facet_value+0 ASC'; } return $orderby; }, 10, 2 );
To sort by label, replace facet_value
with facet_display_value
. For descending order, replace “ASC” with “DESC”.
Sort by arbitrary values
The following example sorts a facet named “day_of_week” by day order.
add_filter( 'facetwp_facet_orderby', function( $orderby, $facet ) { if ( 'day_of_week' == $facet['name'] ) { $orderby = 'FIELD(f.facet_display_value, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")'; } return $orderby; }, 10, 2 );