Overview Crawler Developer API Platform API Tutorials Client Libraries

Customizing Results with the Swiftype Search WordPress Plugin

Swiftype allows you to customize your search experience by applying filters and field weights to your user's queries. This tutorial will walk you through how to apply these modifications with our WordPress plugin.

Understanding query modifiers

Field weight

Applying weight to a field makes it more important in the ranking of search results. For example, you could make tags more important than title.

Filters

Filters allow you to include or exclude content. For example, you could search only posts that were created between a certain time range.

Functional boosts

Functional boosts allow you to boost result scores based on a numeric field. The default WordPress schema does not include any functional boostable fields, but if you add one, you will be able to make use of this option.

WordPress posts search engine schema

The schema describes the structure of the search engine. Think of it as the fields you have available for modification. The names of these fields are what you'll use in your query modifications.

For an overview of the different field types like string and enum, see our field type documentation. For the purposes of this tutorial, it's enough to note that string fields are used for autocomplete and text fields are used for full-text search.

Field Type Description
external_id enum A special field that stores the WordPress post ID
title string The post's title
author string The author's name.
tags string A list of the post's tags
body text The text of the post.
excerpt text The text of the post's excerpt
category enum The category ID number.
url enum The URL for to the post.
image enum The URL for the first image associated with the post.
timestamp date The publication date of the post.
object_type enum The type of post (for example "post", "page", or the name of a custom post type).
updated_at date The date when the post was last updated in Swiftype.

Testing your modifications with curl

It's easy to use our API with curl to try out changes quickly before adding them to your WordPress site. You'll find examples that use curl throughout our Search API documentation. Most Unix-based computers have curl available, and you can download it for Windows as well.

To use the API with curl, it's easiest to submit your requests with JSON parameters.

Here's an example:

Example - The default search results can be found by issuing a query without modifications.
curl -X GET 'https://api.swiftype.com/api/v1/public/engines.json' \
-H 'Content-Type: application/json' \
-d '{
  "engine_key": "YOUR_ENGINE_KEY",
  "q": "search terms here"
}'
  

Example Response

{
    "errors": {},
    "info": {
        "posts": {
            "current_page": 1,
            "facets": {},
            "num_pages": 3,
            "per_page": 20,
            "query": "posts",
            "total_result_count": 41
        }
    },
    "records": {
        "posts": [ ... ]
    }
}

Then, try changing the weight of the fields that will be searched:

Example -  
curl -X GET 'https://api.swiftype.com/api/v1/public/engines/search.json' \
-H 'Content-Type: application/json' \
-d '{
  "engine_key": "YOUR ENGINE KEY",
  "q": "search terms here",
  "search_fields": {
    "posts": ["title^3.0", "tags^2.0", "author^2.0", "body", "excerpt"]
  }
}'
  

Example Response

{
    "errors": {},
    "info": {
        "posts": {
            "current_page": 1,
            "facets": {},
            "num_pages": 3,
            "per_page": 20,
            "query": "posts",
            "total_result_count": 41
        }
    },
    "records": {
        "posts": [ ... ]
    }
}

Note: The results come back in JSON format, so using JSON pretty printer or piping the output to python -m json.tool will help to read them more easily.

Modifying query parameters

To modify the default query parameters on your site, you'll need to use the WordPress add_filter function around the Swiftype plugin's swiftype_search_params function.

This filter function will take one argument $params and return a modified version with the updated query parameters.

Here's the example given above with curl, translated to WordPress. Again, the goal is changing the field weights for title, tags, and author. Since using search_fields will exclude any fields not listed, you must include body and excerpt without a weight.

Example - Changing field weights with search_fields
function swiftype_search_params_filter( $params ) {
    // set the fields to search and their boosts
    $params['search_fields[posts]'] = array( 'title^3', 'tags^2', 'author^2', 'body', 'excerpt' );

    return $params;
}

add_filter( 'swiftype_search_params', 'swiftype_search_params_filter', 8, 1 );
  

You can also limit results by category (Note: If you want to have a search widget that searches within a single category, the Swiftype plugin includes one).

To do so, you'll need to look up the numerical ID for the category, because that's how it's stored in your Swiftype search engine. To find the category ID, look in your WordPress database. You can also find the category ID when you're editing a category in the WordPress Admin. It is shown in the URL as the tag_ID parameter.

Example - Filtering by category with filters
function swiftype_search_params_filter( $params ) {
    // set the categories to allow
    $params['filters[posts][category]'] = array(12, 34, 56);
    return $params;
}

add_filter( 'swiftype_search_params', 'swiftype_search_params_filter', 8, 1 );
  

You can also restrict results to specific post types with the filters parameter.

Example - Filtering by post_type with filters
function swiftype_search_params_filter( $params ) {
    // set the types to allow
    $params['filters[posts][object_type]'] = array( 'post', 'my_custom_post_type' );

    return $params;
  }

  add_filter( 'swiftype_search_params', 'swiftype_search_params_filter', 8, 1 );
  

Numerical and date fields can also be filtered by range. For example, to return only posts written published in 2012 you can use a date range filter:

Example - Date range filter by the timestamp field
function swiftype_search_params_filter( $params ) {
    $params['filters[posts][timestamp][type]'] = 'range';
    $params['filters[posts][timestamp][from]'] = '2012-01-01';
    $params['filters[posts][timestamp][to]'] = '2012-12-31';

    return $params;
}

add_filter( 'swiftype_search_params', 'swiftype_search_params_filter', 8, 1 );
  

This should give you a taste of what's possible with the Swiftype API. Using our API documentation and the schema table above, you can build a custom search experience to meet your needs.

Indexing custom fields

Going beyond what is automatically indexed by the Swiftype WordPress plugin is possible using the swiftype_document_builder filter. This filter takes two arguments: the Document to be sent to Swiftype, and the WordPress post that it represents. Using this filter, you can change the values of fields that have been set, or add new ones.

For example, let's say you had custom fields named zipcode and price. Here's how you could index zipcode as an enum and price as a float:

function update_swiftype_document( $document, $post ) {
   $document['fields'][] = array( 'name' => 'zipcode',
                                  'type' => 'enum',
                                  'value' => get_post_meta( $post->ID, 'zipcode', true ) );
   $document['fields'][] = array( 'name' => 'price',
                                  'type' => 'float',
                                  'value' => get_post_meta( $post->ID, 'price', true ) );

   return $document;
}

add_filter( 'swiftype_document_builder', 'update_swiftype_document', 10, 2 );

Note: Make sure your search engine is not locked in the dashboard before adding custom fields. If it is locked, simply click the lock icon and unlock it.

Customizing autocomplete results

Adding a filter to swiftype_search_params will change how full-text searches are run, but what about the autocomplete drop-down results? The Swiftype autocomplete works by making a request to our API using JavaScript. Therefore, customizations applied in PHP won't have any effect on the results, and you'll need to use JavaScript to add the same filters to the autocomplete search.

By using the swiftypeConfig JavaScript object, you can modify the most important options supported by Swiftype's jQuery autocomplete plugin. Options supported include filters, searchFields, sortField and sortDirection, functionalBoosts, resultLimit, and disableAutocomplete.

Here's the example above of filtering posts to certain categories, translated to JavaScript:

var swiftypeConfig = {
  filters: {
    posts: {
      category: [12, 34, 56]
    }
  }
};

To install the JavaScript, you can edit your theme's header.php file, but it's better to add an action to the [wp_head](http://codex.wordpress.org/Plugin_API/Action_Reference/wp_head) function call to insert your JavaScript code. This wp_head function call is not included in all themes, but it is widely used, so most themes support it.

Example - Using add_action to output the swiftypeConfig JavaScript object
<?php
function swiftype_javascript_config() {
?>
<script type="text/javascript">
var swiftypeConfig = {
  filters: {
    posts: {
      category: [12, 34, 56]
    }
  }
};
</script>
<?php
}

add_action('wp_head', 'swiftype_javascript_config');
?>
  

See the Swiftype jQuery autocomplete library documentation for more examples of customizing autocomplete behavior.

Installing your modifications

You can place your updates in your theme's functions.php but it is advised to create a child theme and put the modification's in the child theme's functions.php.

This step is technically optional but will save your customizations when you upgrade your theme. As the WordPress Codex states:

[T]he functions.php of a child theme provides a smart, trouble-free method of modifying the functionality of a parent theme. Say that you want to add a PHP function to your theme. The fastest way would be to open its functions.php file and put the function there. But that’s not smart: The next time your theme is updated, your function will disappear. But there is an alternative way which is the smart way: you can create a child theme, add a functions.php file in it, and add your function to that file. The function will do the exact same job from there too, with the advantage that it will not be affected by future updates of the parent theme.

Creating a child theme for your modifications is straight forward:

  1. Create a folder in wp-content/themes for your child theme
  2. Add the style.css necessary to declare a child theme.
  3. Create a new functions.php file in your child theme.
  4. Add your Swiftype parameter filter function into your child theme's functions.php

For more details about child themes, see the WordPress documentation.