FacetWP, JSON API, and WP_Query Searches

The following posts are coming up!

Recent Posts



One of the ways that FacetWP works is that it adds <!--fwp-loop--> to the source of your outputted page when it detects you used a search query and it can’t find it’s usual classes. This is so that it’s various features like refreshes and so on. It’s a good thing.

At least it is until you’re trying to use a WP_Query based search to find titles “like” something, and you find your JSON output prefixed…

Mostly Harmless

Most of the time when you see <!--fwp-loop--> in the source code, you don’t care. It doesn’t impact anything and it helps Facet work. This is especially important when you have a ‘weird’ theme or plugins that mess with output.

The issue is that this is how Facet decides if you need that output:

$is_main_query = ( $query->is_archive || $query->is_search || ( $query->is_main_query() && ! $query->is_singular ) );

Most of the time, that makes perfect sense. It just happens that I’m calling search in a place where that output is a bad idea. Like this:

{“id”:6294,”name”:”Alex”,”shows”:”Witches of East End”,”url”:”https:\/\/tv.lezpress.dev\/character\/alex\/”,”died”:”alive”}

Whoops.

Annoying, But Not Impossible, To Fix

After bashing my head in for a while, I grep’d the code for Facet, found where it was being set, and then read the help document on facetwp_is_main_query which told me that I could filter the function.

In this case, I needed to set the value to false to get it to stop outputting, so I used this:

add_filter( 'facetwp_is_main_query', function( $is_main_query, $query ) { return false; }, 10, 2 );

Be careful where you put that by the way. If you put it on all pages, you’ll break your Facets. I put it in the function that generates the JSON output which limits it heavily, just as I want it to.


Posted

in

by

%d bloggers like this: