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 two facets named “number_of_bedrooms” and “number_of_guests” numerically:

<?php
add_filter( 'facetwp_facet_orderby', function( $orderby, $facet ) {

  if ( in_array( $facet['name'], [ 'number_of_bedrooms', 'number_of_guests' ] ) ) { // change 'number_of_bedrooms' and  'number_of_guests' to the name(s) of your facet(s). Add or remove facets from the array if needed.
    $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.

<?php
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 );

More examples

See also