How to set value of the facet by default in Drupal

Sometimes would be nice to activate some facet by default. A lot of people already asked me how to do this, seems it's a good moment to write about it.

It's very simple. Below is a small piece of code, which doing it. You just should launch this code before than your facet will be processed. It means that hook_init in my example is just to test it easy, but you can use some preprocess or block which will execute this code.

 * Implements hook_init().
function test7_init() {
  if (!drupal_is_cli()) {
    // Path of your page with search results.
    if (current_path() == 'search-results') {
      // Name of your searcher.
      // In this case "search_api" is service
      // and "solr_index" is machine name of the index.
      $searcher = 'search_api@solr_index';
      $adapter = facetapi_adapter_load($searcher);
      $url_processor = $adapter->getUrlProcessor();

      // Check if the filter is already active.
      $filter = "field_color:Red";
      $active_items = $adapter->getAllActiveItems();
      if (!isset($active_items[$filter])) {

        // If not, get and tamper with your parameters here.
        $filter_key = $url_processor->getFilterKey();
        $params = $url_processor->fetchParams();
        $params[$filter_key][] = $filter;
        $adapter->setParams($params, $filter_key);

Now my facet is active by default:

Facet by default

I hope that this note was useful for you!