FacetWP REST API
The REST API lets you access raw FacetWP data, which you could use to build custom applications.
Enabling the API
By default, the FacetWP REST API is disabled. To enable it, use this hook:
add_filter( 'facetwp_api_can_access', function( $boolean ) {
return current_user_can( 'manage_options' );
});
Endpoint URL
/wp-json/facetwp/v1/fetch
This endpoint expects a POST
request with 1 parameter: data
. This parameter should be a string (a stringified JSON object).
Example
Let’s retrieve cars
with make = audi
, and also grab choices for the vehicle_type
facet.
Here’s the request JSON, before getting stringified:
var request_data = {
'data': {
'facets': {
'make': ['audi'],
'vehicle_type': []
},
'query_args': {
'post_type': 'cars',
'posts_per_page': 4,
'paged': 1
}
}
};
Here’s the request using javascript’s fetch() method:
var response = fetch('https://yoursite.com/wp-json/facetwp/v1/fetch', {
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('username:password') // base64-encoded
},
'body': JSON.stringify(request_data)
})
.then(response => response.json())
.then(result => console.log(result));
Response data
{
"results":[
1,
2,
3,
4
],
"facets":{
"make":{
"name":"make",
"label":"Make",
"type":"checkboxes",
"selected":[
"audi"
],
"choices":[
{
"value":"audi",
"label":"Audi",
"depth":0,
"count":20
}
]
},
"vehicle_type":{
"name":"vehicle_type",
"label":"Vehicle Type",
"type":"checkboxes",
"selected":[
],
"choices":[
{
"value":"car",
"label":"Car",
"depth":0,
"count":17
},
{
"value":"suv",
"label":"SUV",
"depth":0,
"count":3
},
{
"value":"minivan",
"label":"Minivan",
"depth":0,
"count":0
},
{
"value":"truck",
"label":"Truck",
"depth":0,
"count":0
},
{
"value":"van",
"label":"Van",
"depth":0,
"count":0
}
]
}
},
"pager":{
"page":1,
"per_page":4,
"total_rows":20,
"total_pages":5
}
}
Trigger the indexer programmatically
You may need to trigger the indexer programmatically if posts aren’t saved via the normal /wp-admin/.
The second code sample on the above-linked section shows how to force FacetWP to re-index a specific post.