How can I exclude certain posts from search results using the Swiftype WordPress plugin?

I have a few posts in my WordPress site that I never want to show in search results. How can I exclude them?

There are a few ways to accomplish this with the Swiftype Search. The simplest way is to add the posts you want to exclude to a category, and then filter out that category from the search results. Keep in mind that posts can belong to multiple categories, so you can create a new category just for this purpose.

First, create the category you want to use to exclude posts from the search. Then add the posts to that category. Next, you need to find the database ID of the category. You can see this in the URL when you look at the category in the WordPress admin dashboard.

For example, if the URL is:

http://my-wp-site.com/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=162&post_type=post

The category ID is 162.

To restrict your search to exclude the category, you’ll need to add a filter to your search parameters.

To do this, add a WordPress filter function to your theme’s functions.php file to modify the Swiftype search parameters. The filter will include all categories except the one you found above. This is done by adding a ! in front of the category ID.

function swiftype_search_params_filter( $params ) {
    // Include all categories except 162
    $params['filters[posts][category]'] = array( '!162' );
    return $params;
}
	
add_filter( 'swiftype_search_params', 'swiftype_search_params_filter' );

You can exclude multiple categories by adding them to the array like this:

array( '!162', '!13', '!45' )`

Once you add this to your functions.php and save the file, the category exclusion will take effect. However, the swiftype_search_params_filter function will only affect searches that are submitted through WordPress and the autocomplete results are made directly to Swiftype’s servers from the user’s web browser via JavaScript. Therefore, to make the autocomplete results match the search results, you’ll need to add a swiftypeConfig object to customize the JavaScript query parameters as well.

To accomplish this, add an action for wp_head to your theme’s functions.php and set query params with a filter for the same allowed category IDs:

function swiftype_javascript_config() {
?>
<script type="text/javascript">
var swiftypeConfig = {
  filters: {
    posts: {
      category: ["!162"]
    }
  }
};
</script>
<?php
}
	
add_action( 'wp_head', 'swiftype_javascript_config' );

To learn more about customizing WordPress search results, read our WordPress customization tutorial.