Plugins

WP Search with Algolia Tips and Tricks

Let’s face it; the native WordPress search is mediocre at best. The search algorithm takes only post title, content, and excerpt into consideration when generating search results. It also places extreme relevance on exact matches, which can lead to irrelevant results being returned for search queries.

The WP Search with Algolia plugin for WordPress allows you to almost instantly improve the quality of search results by sending the content of your WordPress site to Algolia for indexing. Algolia provides configuration options for things like custom rankings, sorting, fuzzy matching, and personalization of search results, which greatly improves the overall quality of search results.

WP Search with Algolia handles the indexing of all WordPress content, images, and custom fields by sending data directly to Algolia. It fully replaces the default WordPress search algorithm and can also integrate Algolia’s InstantSearch feature.

This is the official banner for WP Search with Algolia WordPress plugin. It's green with clock icon in the background and the words "Improve search on your site," along with the WebDevStudios logo in the bottom right corner.

Benefits of Using Algolia Over Native WordPress Search

  • Speed – The Algolia API returns relevant search results in milliseconds.
  • Typo Tolerance – Typo tolerance allows users to make mistakes while typing and still find the records they seek.
  • Custom Ranking – Define custom rankings based on popularity, customer behavior, and other business metrics.
  • Analytics – Analyze queries to get a deeper understanding of top search terms, locations, conversion rates of queries, etc.
  • Facets – Build a faceted experience with refinements that help avoid “no results” screens.

Tips and Tricks

To get the most out of Algolia and WP Search with Algolia, I’m going to highlight some powerful Filter Hooks and Constants of the plugin that allow developers to alter or modify the way data is sent to Algolia for indexing.

Image Sizes

By default, WP Search with Algolia sends image data for the default thumbnail image size only. The thumbnail image size is used as the preview image within the autocomplete and instantsearch components provided by the plugin.

Using the algolia_post_images_sizes filter, we can extend or modify the images sizes indexed and returned by the Algolia search. This filter is really useful when customizing the look and feel of the autocomplete or instantsearch plugin templates.

// functions.php
function wds_algolia_set_image_sizes() {
	return [
		'cta',
		'medium',
		'thumbnail',
		'hero',
	];
}
add_filter( 'algolia_post_images_sizes', 'wds_algolia_set_image_sizes', 10, 2 );

The code sample above adds four registered image sizes to the Algolia index using the algolia_post_images_sizes filter.

Indexing Custom Fields

In WordPress, custom fields (or post meta) are fields in the database that are used to store additional information about a post or a page. By default, custom fields are not searchable by Algolia, unless the fields have been added to the index.

Popular plugins such as Advanced Custom Fields and Meta Box have made working with custom fields second nature to WordPress developers. Having the ability to index custom fields can improve overall search quality and search relevance for users.

One benefit of using WP Search with Algolia over native WordPress search is you can push custom field data to Algolia and ensure these fields are indexed as searchable attributes.

// functions.php
function wds_algolia_custom_fields( array $attributes, WP_Post $post ) {

	// Eligible post meta fields.
	$fields = [
		'display_date',
		'duration',
		'file_type',
		'transcript',
	];

	// Loop over each field...
	foreach ( $fields as $field ) {

		// Standard WordPress Post Meta.
		$data = get_post_meta( $post->ID, $field );

		// Advanced Custom Fields.
		// @see https://www.advancedcustomfields.com/resources/get_field/
		$data = get_field( $field, $post->ID );

		// Only index when a field has content.
		if ( ! empty( $data )  ) {
			$attributes[ $field ] = $data;
		}
	}

	return $attributes;
}
add_filter( 'algolia_post_shared_attributes', 'wds_algolia_custom_fields', 10, 2 );
add_filter( 'algolia_searchable_post_shared_attributes', 'wds_algolia_custom_fields', 10, 2 );

The code sample above uses the algolia_post_shared_attributes and algolia_searchable_post_shared_attributes filters to add four custom fields and their corresponding data to the Algolia index.

Index Prefix for Multiple Environments

You’re likely to have multiple environments for your WordPress site: local, development, staging, and production. In a perfect world, each environment would each have their own unique Algolia index, or you could run the risk indexing search results from a non-production environment.

By default, WP Search with Algolia prefixes the index name with wp_. This prefix is stored in the WP Options table and is updatable by visiting Algolia Search > Settings in your WordPress admin.

This is a screen grab that shows the WP Search with Algolia Index Prefix setting. To the left in bold font, it says, "Index name prefix." In a white field box, it say wp_. Beneath that is says, "This prefix will be prepended to your index names."

This works perfectly fine if you are running a single environment; however, if you are pushing and pulling content across multiple environments, this can be problematic as you need to update the index name each time content is synced.

To solve this issue, you can use the ALGOLIA_INDEX_NAME_PREFIX constant. This constant can be used to define the prefix outside of the WordPress database by adding it directly to the wp-config.php file of each environment.

// wp-config.php.
define( 'ALGOLIA_INDEX_NAME_PREFIX', 'dev_' ); // dev_searchable_posts
// wp-config.php.
define( 'ALGOLIA_INDEX_NAME_PREFIX', 'prod_' ); // prod_searchable_posts

Creating a unique index for each WordPress environment will reduce the risk of issues arising in production and allow for more thorough testing by indexing the content of each specific environment.

WordPress 5.5 introduced a new function, wp_get_environment_type, that retrieves the current environment type (local, development, staging, or production). Once managed hosts begin adopting and supporting environment type variables, you could define index prefixes at the theme level in functions.php.

// functions.php
switch ( wp_get_environment_type() ) {
	case 'production':
		define( 'ALGOLIA_INDEX_NAME_PREFIX', 'prod_' );
		break;

	case 'staging':
		define( 'ALGOLIA_INDEX_NAME_PREFIX', 'staging_' );
		break;

	case 'local':
	case 'development':
		define( 'ALGOLIA_INDEX_NAME_PREFIX', 'dev_' );
		break;
}

Excluding by Post Types

WP Search with Algolia does not index post types that have exclude_from_search set to true. This works in most cases; however, there may be situations where a third-party plugin or another system has registered a post type without exclude_from_search and you want to exclude it from being indexed.

For these cases, you can use the algolia_searchable_post_types filter to manually exclude the post type.

// functions.php
function wds_algolia_exclude_post_types( $post_types ) {

	// Ignore these post types.
	unset( $post_types['acf-field_group'] );
	unset( $post_types['testimonials'] );
	unset( $post_types['forms'] );

	return $post_types;
}
add_filter( 'algolia_searchable_post_types', 'wds_algolia_exclude_post_types' );

Excluding Individual Posts

There may be times where, for whatever reason, you need to exclude a specific post or posts from being indexed by Algolia. To do this, create a checkbox field using Advanced Custom Fields and attach the field group to each post type you require indexing control.

This is a screen grab that shows how to exclude a specific post or posts from being indexed by Algolia with ACF Checkbox Field Group. At the top, the field says Post Options. Below that there are four columns: Order, Label, Name, and Type. Under order, it shows the digit one. Under label, it says, "Exclude from search." Under name it shows, exclude underscore from underscore search. Under type, it says Checkbox. Beneath all that is a blue button that says + Add Field.

On the posts or pages you wish to exclude from the search, check the checkbox to mark the content as non-indexable.

This is a screen grab that shows the ACF exclude from search checkbox option. At the to, it says, "Post options." Beneath that it says, "Exclude from Search." Beneath that, it says, "Do NOT index post." Next to that there is a square field box that is checked off.

In functions.php, use the algolia_should_index_searchable_post and algolia_should_index_post filters to evaluate the custom field; and if checked, return a false value to the should_index filters.

// functions.php
function wds_algolia_exclude_post( $should_index, WP_Post $post ) {
 
  // If a page has been marked not searchable
  // by some other means, don't index the post.
  if ( false === $should_index ) {
     return false;
  }


  // ACF Field.
  // Check if a page is searchable.
  $excluded = get_field( 'exclude_from_search', $post->ID );
 
  // If not, don't index the post.
  if ( 1 === $excluded ) {
     return false;
  }
 
  // If all else fails, index the post.
  return true;
}
add_filter( 'algolia_should_index_searchable_post', 'wds_algolia_exclude_post', 10, 2 );
add_filter( 'algolia_should_index_post', 'wds_algolia_exclude_post', 10, 2 );

Wrapping Up

WP Search with Algolia provides an all-in-one solution for improving the overall quality of your WordPress search results. Not only does the plugin provide functionality searching and displaying search results on standard WordPress themes, it can also be used for content indexing purposes only for Headless WordPress projects.

Comments

1 thought on “WP Search with Algolia Tips and Tricks

Have a comment?

Your email address will not be published. Required fields are marked *

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupportunifiedupdatesvaultwebsitewordpress