12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Feb 21, 2022

Prefiltering Content by a Facet Choice in WP Grid Builder

Sridhar Katakam

When using a WP Grid Builder facet like the Radio facet where the data source is a Taxonomy such as filtering FAQ items by FAQ Category, the default behavior is to see all the posts and the default label of “All” being highlighted/selected.

Now let’s say the requirement is to NOT show the default label and have the first (or a specific) taxonomy term highlighted/selected and only the corresponding filtered posts appear in the grid.

Removing “All” default label in the facet’s BEHAVIOUR tab will not show it on the front end.

But what about prefiltering the grid? WPGB’s /facet/query_string to the rescue!

Here’s the base code (see Note 1 below) being used to filter the items by General term on https://centurion-dubai.com/faq/:

add_filter( 'wp_grid_builder/facet/query_string', 'wpdd_filter_query', 10, 3 );
function wpdd_filter_query( $query_string, $grid_id, $action ) {

	// If the content is not filtered on first render.
	if ( 'render' === $action && empty( $query_string ) ) {
		
		$query_string = [
			'faq_categories' => [ 'general' ],
		];

	}
	
	return $query_string;
	
}

Added that using the Code Snippets plugin and set to run on front end only.

Note 1: It is recommended to restrict the above filter based on the grid ID (if using WP Grid Builder’s grid) or a view (like a specific Page or a CPT archive etc.). Here’s the actual code I used on the centurion-dubai site:

add_filter( 'wp_grid_builder/facet/query_string', 'wpdd_filter_query', 10, 3 );
function wpdd_filter_query( $query_string, $grid_id, $action ) {

	// If the content is not filtered on first render.
	if ( 'render' === $action && empty( $query_string ) && is_post_type_archive( 'faq' ) ) {
		
		$query_string = [
			'faq_categories' => [ 'general' ],
		];

	}
	
	return $query_string;
	
}

Note 2: When the grid is being prefiltered, the URL will automatically change to indicate the prefiltered choices. Ex:

https://centurion-dubai.com/faq/

becomes

https://centurion-dubai.com/faq/?_faq_categories=general

If there are multiple facets on a given page for a given grid, it is possible to have the grid prefiltered by any number of those facets as shown in the example on the doc.

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-ocalendar-check-omagnifiercrossmenuchevron-downarrow-right