→ Customize the FacetWP Sort Options

FacetWP includes lightweight sorting functionality. Below is the default sort box appearance. FacetWP includes 5 options (including the default), but also allows for the creation of custom sort options.

sort-options

How the Sort Box Works

If you recall, each FacetWP Template has a field called “Query Arguments”. That field returns an array of parameters, such as:

<?php
return array(
    'post_type' => 'post',
    'posts_per_page' => 10,
    'orderby' => 'date',
    'order' => 'desc',
);

That array gets passed to WP_Query, which uses that information to figure out (a) which posts to fetch from the database, and (b) in which order.

The sort box works by modifying the Query Arguments — such as order and orderby — right before they’re passed to WP_Query.

Default Sort Options

FacetWP’s facetwp_sort_options hook gives you control over the options to display (and how to handle each option). Below are the default arguments.

$options = array(
    'default' => array(
        'label' => __( 'Sort by', 'fwp' ),
        'query_args' => array()
    ),
    'title_asc' => array(
        'label' => __( 'Title (A-Z)', 'fwp' ),
        'query_args' => array(
            'orderby' => 'title',
            'order' => 'ASC',
        )
    ),
    'title_desc' => array(
        'label' => __( 'Title (Z-A)', 'fwp' ),
        'query_args' => array(
            'orderby' => 'title',
            'order' => 'DESC',
        )
    ),
    'date_desc' => array(
        'label' => __( 'Date (Newest)', 'fwp' ),
        'query_args' => array(
            'orderby' => 'date',
            'order' => 'DESC',
        )
    ),
    'date_asc' => array(
        'label' => __( 'Date (Oldest)', 'fwp' ),
        'query_args' => array(
            'orderby' => 'date',
            'order' => 'ASC',
        )
    )
);

As you can see, each option has a query_args property, which is the actual sorting logic – it lets you alter WP_Query and override any necessary attributes (such as order & orderby).

How to Add New Sort Options

Let’s create a new option to sort by the (numerical) custom field named num_downloads.

<?php
function my_facetwp_sort_options( $options, $params ) {
    $options['num_downloads'] = array(
        'label' => 'Most Downloads',
        'query_args' => array(
            'orderby' => 'meta_value_num', // sort by numerical custom field
            'meta_key' => 'num_downloads', // required when sorting by custom fields
            'order' => 'DESC', // descending order
        )
    );
    return $options;
}

add_filter( 'facetwp_sort_options', 'my_facetwp_sort_options', 10, 2 );

How to Remove Sort Options

To remove an existing option, simply unset the appropriate array key. For example:

<?php
function my_facetwp_sort_options( $options, $params ) {
    unset( $options['title_desc'] );
    return $options;
}

add_filter( 'facetwp_sort_options', 'my_facetwp_sort_options', 10, 2 );