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.
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
- Indexing Custom Fields
- Index Prefix for Multiple Environments
- Excluding by Post Type
- Excluding Individual Posts
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 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.
On the posts or pages you wish to exclude from the search, check the checkbox to mark the content as non-indexable.
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.
Thanks for mentioning Meta Box. We’ve been using your WP Search with Algolia plugin on our site and love it. It’s a really great plugin. We also wrote a tutorial on implementing it on our website.
Thanks for this information you gave us. I managed to index medium size images, but how do I get those in use?
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
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
Hi Daz,
Something like the code in the following GitHub gist should help.
https://gist.github.com/tw2113/64c1598758f0540265dce8cbd7aa590a
This checks the current product/post getting indexed, and retrieves if it’s marked as a hidden catalog item for WooCommerce. If it is considered hidden, we return false to make it not get indexed. Otherwise it should get indexed.
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!
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.
Here it is!
https://www.algolia.com/doc/guides/managing-results/optimize-search-results/override-search-engine-defaults/how-to/how-can-i-make-queries-within-the-middle-of-a-word/
Actually, i just wanna search for SKU. But my problem is sku is too long ( more than 6 characters )… that why i wanna change it!
Thanks bro!
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.
I’m using this successfully – thanks for the article.
I am having One issue though and wondering if you have any thoughts –
https://www.algolia.com/doc/guides/managing-results/refine-results/geolocation/
I’m trying to pass geolocation fields from ACF like:
“_geoloc”: {
“lat”: 40.639751,
“lng”: -73.778925
}
I’m not sure how to build a nested array like this based on your instructions above.. Any thoughts?
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`
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
Hi, Michail. Thanks for using WP Search with Algolia. At the WordPress plugin repo, we have a Support page where you can submit your request for support and interact with the developer directly. Thank you.
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.
Hi, David. Thanks for using WP Search with Algolia. At the WordPress plugin repo, we have a Support page where you can submit your request for support and interact with the developer directly. Thank you. https://wordpress.org/support/plugin/wp-search-with-algolia/