→ facetwp_facet_orderby

Overview

This filter lets you control the display order of facet values.

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 = array(
    'name' => 'my_facet',
    'type' => 'checkboxes',
    'source' => 'tax/category',
    ...
);

Usage

Sort the label numerically (in ascending order)

<?php
function sort_facet_numerically( $orderby, $facet ) {
    if ( 'my_facet' == $facet['name'] ) {
        $orderby = 'f.facet_display_value+0 ASC';
    }
    return $orderby;
}

add_filter( 'facetwp_facet_orderby', 'sort_facet_numerically', 10, 2 );

Sort by arbitrary values

<?php
function facet_custom_sort( $orderby, $facet ) {
    if ( 'day_of_week' == $facet['name'] ) {
        // to sort by raw value, use "f.facet_value" instead
        $orderby = 'FIELD(f.facet_display_value, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")';
    }
    return $orderby;
}

add_filter( 'facetwp_facet_orderby', 'facet_custom_sort', 10, 2 );