From 857c1ff7de1408871088a4584fed410d29f648ca Mon Sep 17 00:00:00 2001 From: Jacob Peattie Date: Thu, 21 Jul 2022 15:15:48 +1000 Subject: [PATCH] Document window.epAutosuggestItemHTMLFilter --- docs/theme-integration.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/docs/theme-integration.md b/docs/theme-integration.md index d14f2a20fc..c66ac25d54 100644 --- a/docs/theme-integration.md +++ b/docs/theme-integration.md @@ -32,4 +32,33 @@ You could display the loading gif while suggestions are being fetched with this .is-loading .loading-indicator { display: block; } -``` \ No newline at end of file +``` + +### Customize Suggestion Markup + +When ElasticPress Autosuggest renders the suggestion list each item is run through a `window,epAutosuggestItemHTMLFilter()` function, if such a function exists. Therefore you can provide your own markup for suggestions by defining this function from your theme or plugin. This can be used to include other fields in the suggestion. + +The `epAutosuggestItemHTMLFilter()` function should return the HTML for the suggestion as a string, and accept 4 parameters: + +1. `itemHTML` _(string)_ The suggestion HTML as a string. +2. `option` _(object)_ The Elasticsearch record for the suggestion. +3. `i` _(int)_ The index of the suggestion in the results set. +4. `searchText` _(string)_ The search term. + +This example uses the function to add the post date to the suggestion: + +``` +window.epAutosuggestItemHTMLFilter = (itemHTML, option, i, searchText) => { + const text = option._source.post_title; + const url = option._source.permalink; + const postDate = new Date(option._source.post_date).toLocaleString('en', { dateStyle: 'medium' }) + + return `
  • + + ${text} (${postDate}) + +
  • `; +} +``` + +Note that the `class`, `id`, `role`, `aria-selected`, `data-url`, and `tabindex` attributes in the returned markup should match the default values for those attributes, as they do in the example, to ensure that Autosuggest functions as normal.