Created
September 14, 2020 15:47
-
-
Save brandwaffle/e211ba57cc2b09ab4435d4ccd2ed1df1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
let filterElasticsearchResponse = false; | |
let searchTerm; | |
$.ajaxSetup({ | |
beforeSend: function(xhr, settings) { | |
if( settings.url == window.epas.endpointUrl) { | |
filterElasticsearchResponse = true; | |
searchTerm = settings.headers['EP-Search-Term']; | |
} | |
}, | |
dataFilter: function (data, type) { | |
const parsedData = JSON.parse(data); | |
// return if not elasticpress search | |
if( !filterElasticsearchResponse ) { | |
return JSON.stringify(parsedData);; | |
} | |
const { hits } = parsedData; | |
if( !hits ) { | |
return JSON.stringify(parsedData);; | |
} | |
hits.hits.forEach(hit => { | |
const title = hit._source.post_title; | |
const modelNumbers = hit._source.meta.model_number; | |
if( modelNumbers.length ) { | |
hit._source.post_title = `(${modelNumbers[0].value}) - ${title}`; | |
} | |
}); | |
// append `ALL RESULTS` when there is more results than displaying | |
const total = hits.total; | |
if ( total > 5 ) { | |
const limitedResults = hits.hits.slice( 0, 5 ); | |
const allResultsLink = { | |
_source: { | |
post_id: Math.floor( Math.random() * 100000 ), | |
permalink: `/?s=${searchTerm}`, | |
post_title: `Displaying 5 of ${total} results. View all results.`, | |
} | |
} | |
limitedResults.push( allResultsLink ); | |
// reset the array that goes back to EP | |
hits.hits = limitedResults; | |
} | |
const newData = JSON.stringify(parsedData); | |
return newData; | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment