Sort Search Results Page by latest blog

Hi guys,

I am using the site search module for my blogs on hubspot but I notice it returns blogs in random order. Is there a way I can have this sorted by published date to show the most recent first?

Thanks!

The Search API returns results in order of relevance (e.g. have the most occurences of the search term in the HTML title, Meta description, H1 and so on), it’s not random.

You can increase the relevancy score of pages recently published like so: boostRecent=7d. This will increase the score of pages published within the last 7 days. That said, I’m not sure it’s possible to do this with the default search module, this may only be available if you use the Search API and develop your own search functionality (if you’re doing that you could order them by published date yourself). More in the documentation here.

Alternatively, you could write some JS to reorder the items on your search results page after they’ve been returned by the search function.

Thanks @piersg
Could you please tell me how I might use JS to reorder them once they have displayed on the page? For example, order by publishedDate.

Thanks

It would depend on how the information in your post elements that are returned by the search function is structured. For me it would be like this:

var posts = document.getElementsByClassName('post-item'); // the blog posts
var postsArr = []; // empty array to sort
for (i = 0, iLen = posts.length; i < iLen; i++) {
 // get the date which I've set as a data attribute (e.g. data-date="01 Jan 2021") so it's easily accessible
 let date = posts[i].dataset.date;
 date = Date.parse(date); //turn that into unix timestamp
 let obj = {
 'post' : posts[i],
 'date' : date
 }
 postsArr.push(obj); // push that info to the array
}
// sort the array by unix timestamp, most recent first
postsArr.sort(function(a, b) {
 return -a.date - -b.date;
});
// the wrapping parent of the search results section
var parent = document.querySelector('#search-results .row.small-row');
// add the ordered array to the parent
postsArr.forEach(function(el) {
 parent.append(el.post);
});