As I implement more and more aspects of FacetWP, I find more and more ways to manipulate the searches. At first I only added in the features that let people easily search for multiple aspects at once. But I hadn’t yet added in any features to sorting.

Sorting and Ordering

The way Facets generally work is that you can easily organize all ‘types’ together, so if you wanted to search for everything that crossed four separate categories, it was very easy. In addition, you can extend it to search meta data as well.

Sorting, on the other hand, is changing the order of the results. For example, if you wanted to search for everyone with terms A, B, and D, and post meta foo, but order them based on post meta bar, you can!

A Practical Example

I always do better with examples I can wrap my hands around.

Take television shows. Take a list of 500 TV shows, and have them include the following taxonomies:

  • Genres (drama, sitcom, etc)
  • Airdates (Year to Year)
  • Tropes (common tropes)
  • Number of characters
  • Number of dead characters

That’s enough for now.

With that list, and a couple facets, you can concoct a smaller list of all sitcoms that aired in between 2014 and 2016 (inclusive), with a trope of ‘sex workers.’ The answer is 4 by the way. By default, the list displays alphabetically.

But. What if you wanted to order them by the ones with the most characters first?

That’s sorting.

The Code

Okay so how do we add this in? Functions!

Facet comes with quite a few defaults, but it lets you add your own sort options. The two things I’m going to show below are how to rename the display labels for some of the defaults, and how to add in one new option for the most number of characters:

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

function facetwp_sort_options( $options, $params ) {

	$options['default']['label']    = 'Default (Alphabetical)';
	$options['title_asc']['label']  = 'Name (A-Z)';
	$options['title_desc']['label'] = 'Name (Z-A)';

	if ( is_post_type_archive( 'DOMAIN_shows' ) ) {

		$options['most_characters'] = array(
			'label' => 'Number of Characters (Descending)',
			'query_args' => array(
				'orderby'  => 'meta_value_num', // sort by numerical
				'meta_key' => 'DOMAIN_char_count',
				'order'    => 'DESC', // descending order
			)
		);
	}

I have this wrapped in a check for is_post_type_archive because I don’t want the options to show on other pages. The meta key is the name of the meta key you’re going to use to sort by (I have key that updates every time a post is saved with a count of characters attached) and the orderby value is one of the ones WP Query can use.

End result?

A dropdown with the options

Looks nice!

Reader Interactions

%d bloggers like this: