Skip to content
Michael Beckwith edited this page Jun 10, 2024 · 8 revisions

Integrate Algolia Search for WordPress with WPML.

Introduction

WPML helps WordPress users offer different content to their users depending on the locale of the displayed page.

In this guide you will learn how to filter the search results based on the current locale.

Initial Setup

Before being able to filter on the locale, we need to ensure that:

  • The locale is added to every post record in Algolia
  • The locale attribute is considered as being a facet by adding it to the index settings

Copy paste the following directly in the functions.php file of your active theme.

You can also create a new file like: wp-content/plugins/mu-plugins/algolia-wpml.php. This will automatically be picked up by WordPress and be run and has the benefit of not requiring you to change your theme files.

<?php

// Add the locale of every post to every record of every post type indexed.
function add_locales_to_records( array $attrs, WP_Post $post ) {
    // Here we make sure we push the post's language data to Algolia.
    $attrs['wpml'] = apply_filters( 'wpml_post_language_details', null,  $post->ID );
    return $attrs;
}

add_filter( 'algolia_post_shared_attributes', 'add_locales_to_records', 10, 2 );
add_filter( 'algolia_searchable_post_shared_attributes', 'add_locales_to_records', 10, 2 );

// Register the locale attribute as an Algolia facet which will allow us to filter on the current displayed locale.
function add_locale_to_facets( array $settings ) {
    $settings['attributesForFaceting'][] = 'wpml.locale';

    return $settings;
}

add_filter( 'algolia_searchable_posts_index_settings', 'add_locale_to_facets' );
add_filter( 'algolia_posts_index_settings', 'add_locale_to_facets' );

// Expose the current locale of the displayed page in JavaScript.
function enqueue_locale() {
    wp_add_inline_script( 'algolia-search', sprintf('var current_locale = "%s";', get_locale()), 'before' );
}

add_action( 'wp_enqueue_scripts', 'enqueue_locale', 99 );

After you have implemented the above code, you need to re-index every index you are using from the "Algolia Search -> Autocomplete" page or "Algolia Search -> Search Page" page.

You also need to click the "Push Settings" button for every used index.

Filter search results page based on current locale

In the previous section you should have put in place all the logic required for you to filter your results based on the current locale.

Now what you need to do is tell InstantSearch.js and Autocomplete.js to "facet" on the "locale" attribute of your post records.

To do so, you first need to copy instantsearch.php template file in your own theme in order to customize it without changing the plugin's files.

Once that is done, you need to filter on the locale facet. Add the filters line to your instantsearch initialization:

WP Search with Algolia version 1.8.x and earlier

/* Instantiate instantsearch.js */
var search = instantsearch({
  appId: algolia.application_id,
  apiKey: algolia.search_api_key,
  indexName: algolia.indices.searchable_posts.name,
  urlSync: {
    mapping: {'q': 's'},
    trackedParameters: ['query']
  },
  searchParameters: {
    facetingAfterDistinct: true,
    highlightPreTag: '__ais-highlight__',
    highlightPostTag: '__/ais-highlight__',
    filters: 'wpml.locale:"' + current_locale + '"', // This is the line we added.
  }
});

WP Search with Algolia version 2.0.x and later

search.addWidgets([
	...
	instantsearch.widgets.poweredBy({
		container: '#algolia-powered-by'
	}),

	instantsearch.widgets.configure({
    facetingAfterDistinct: true,
    highlightPreTag: '__ais-highlight__',
    highlightPostTag: '__/ais-highlight__',
    filters: 'wpml.locale:' + current_locale // This is the line we added.
	})
]);

If you are using Algolia with the native WordPress search template, you can get the filtering in place with the following.

function algolia_filter_backend_search_params( $params ) {
	$current_lang = apply_filters('wpml_current_language', NULL);

	if ( ! $current_lang ) {
		return $params;
	}

	$params['filters'][] = 'language:' . $current_lang;
	return $params;
}
add_filter( 'algolia_search_params', 'algolia_filter_backend_search_params' );

Now your results on the dedicated search page should be properly filtered.

For the autocomplete dropdown experience, you need to make a similar change.

First, copy the autocomplete.php file to your own theme, then make the following change to your file:

WP Search with Algolia version 1.8.x and earlier

source: algoliaAutocomplete.sources.hits(client.initIndex(config['index_name']), {
  hitsPerPage: config['max_suggestions'],
  attributesToSnippet: [
    'content:10'
  ],
  highlightPreTag: '__ais-highlight__',
  highlightPostTag: '__/ais-highlight__',
  filters: 'wpml.locale:"' + current_locale + '"', // This is the added line.
}),

WP Search with Algolia version 2.0.x and later

source: algoliaHitsSource( client.initIndex( config[ 'index_name' ] ), {
  hitsPerPage: config['max_suggestions'],
  attributesToSnippet: [
    'content:10'
  ],
  highlightPreTag: '__ais-highlight__',
  highlightPostTag: '__/ais-highlight__',
  filters: 'wpml.locale:"' + current_locale + '"', // This is the added line.
}),

After this change, your autocomplete dropdown results should also be filtered by the current locale.