Introducing the 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' );
});

Important: secure the API using authentication, otherwise anonymous users will be able to access private data!

Endpoint URL

<example.com>/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:

let request_data = {
  'facets': {
    'make': ['audi'],
    'vehicle_type': []
  },
  'query_args': {
    'post_type': 'cars',
    'posts_per_page': 4,
    'paged': 1
  }
}

Note: query_args accepts any WP_Query params (like tax_query, meta_query, etc).

Here’s the request using javascript’s fetch() method:

const response = fetch('https://yoursite.com/wp-json/facetwp/v1/fetch', {
  'method': 'POST',
  'headers': {
    'Authorization': 'Basic ' + btoa('username:password') // base64-encoded
  },
  'body': {
    'data': JSON.stringify(request_data) // stringified!
  }
})
.then(function(response) {
  console.log(response);
});

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
  }
}