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 dark gray and salmon orange with the Algolia logo on the right and the words "WordPress WP Search with Algolia" 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( $sizes ) {
	// 'thumbnail' will already be coming in with the $sizes array.
	foreach( [ 'cta', 'medium', 'hero' ] as $size ) {
		$sizes[] = $size;
	}
	return $sizes;
}
add_filter( 'algolia_post_images_sizes', 'wds_algolia_set_image_sizes', 10, 2 );

The code sample above adds three other 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 two Algolia indexes.

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

If you don’t want to code this part yourself, or want greater control over not indexing content based on “No index” settings from plugins like Yoast, All In One SEO, Rank Math, or SEOPress, please consider checking out our premium WP Search with Algolia Pro addon.

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 for searching and displaying search results on standard WordPress themes, it can also be used for content indexing purposes only for Headless WordPress projects.


Editor’s Note: This blog post was updated on February 20, 2024 by WebDevStudios Backend Engineer Michael Beckwith.

Comments

15 thoughts on “WP Search with Algolia Tips and Tricks

  1. Thanks for this information you gave us. I managed to index medium size images, but how do I get those in use?

    1. Good day to you.

      If you are referring to in the instantsearch results, then I believe you’re going to want to customize the instantsearch.php template file and these lines specifically:

      https://github.com/WebDevStudios/wp-search-with-algolia/blob/2.1.0/templates/instantsearch.php#L49-L55

      You’ll want to check and confirm with your Algolia instance on the property to reference, but the spots that look like `data.images.thumbnail` would need to be updated to match the index you set for the indexing portion. For the sake of this reply, I’m going to assume that is `medium`. So those would need to be changed to `data.images.medium` to reference the correct property.

      Same steps will apply if you are referring to Autocomplete, and the lines in question for that can be found at https://github.com/WebDevStudios/wp-search-with-algolia/blob/2.1.0/templates/autocomplete.php#L23-L25

      Information about customizing the templates can be found over at https://github.com/WebDevStudios/wp-search-with-algolia/wiki/Customize-Templates

  2. Nice.
    just wondering how I might filter hidden woocommerce products?? The catalog_visibility field isn’t being indexed. Adding an ACF seems redundant for woocomemrce hidden products???
    I appreciate any advice.
    Daz

  3. Thanks for sharing!
    I have another question about “Query in the middle of a word”.
    For example I have a product with the character xxxABC123, I want to type “ABC” or “123”.
    I have read the article on Algolia’s website but don’t know how to edit for woocommerce. Please help me to do this!
    Thank you once more time!

    1. Hey Minh,

      Can you link us to the article you are referring to? I’m not sure about this one offhand and how to possibly help with it. It’s potentially an Algolia Dashboard configuration change needing made, outside of the WP Search with Algolia portion of the overall process and integration.

      1. Just making sure I’m understanding, you’re wanting to change where the search takes place in a given query, because the SKU is long?

        Based on the link provided, thank you for that, I think we’d want to get you adding in the sku to shared attributes spot, and them parsed out similar to what the docs page shows where you’re breaking it up into smaller chunks. Then once those are indexed, add that new index to the searchable parts in your Algolia dashboard.

    1. Hi Jay,

      Can you provide what code you’re using thus far? It’ll help us make sure we’re providing accurate amended snippets to help here. For example if you’re adding this via a callback on say the `algolia_post_shared_attributes` hook from Darren’s example above.

      Going to assume a moment, but if you have something like this:

      “`
      $geodata = get_field( ‘geodata_field’, $post->ID );

      if ( ! empty( $geodata ) ) {
      $attributes[ ‘_geoloc’ ] = $geodata;
      }
      “`
      And `$geodata` is that JSON data directly, then I think you’d want to do this:

      “`
      $attributes[‘_geoloc’][] = $geodata;
      “`

      This turns the `$attributes[‘_geoloc’]` index into a nested array itself.

      If your latitude and longitude are stored in their own then perhaps something like this:

      “`
      $geolat = get_field( ‘geodata_lat’, $post->ID );
      $geolng = get_field( ‘geodata_lng’, $post->ID );
      $geodata = [ ‘lat’ => $geolat, ‘lng’ => $geolng ];
      $attributes[‘_geoloc’][] = json_encode( $geodata );
      “`
      This would construct an array with the key/value pairs, and then encode and store in the same way on the returned `$attributes`

  4. hello my name is Michail Kaipis and i am a software developer, i havent figured out how to use your plugin to include filters in my search

    i am trying to use your plugin with algolia search in wp and i want to add search filters like for a spesific category, i looked that the algolia api has an option for this to happen with php for example:

    // Search the “category” facet for values matching “phone”
    // in records having “Apple” in their “brand” facet.
    $index->searchForFacetValues(“category”, “phone”, [
    ‘filters’ => ‘brand:Apple’
    ]);

    i am wondering if its posible to make the filtered search from your plugin directly
    if its possible please let me know how its done

    thanks a lot for your time
    Michail

  5. I am facing the issue that the plugin writes me the same content to almost each post. The title and all other parameters are different, but the “content” is the same.

Have a comment?

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

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