Monday, November 20, 2017

Modifying the query template for the Highlighted Content modern web part – a very brittle solution

image

The highlighted content web part in modern pages is the successor for the content search web part. It does a pretty decent job, but people like me who like to tune what we get back want some more expert settings, much like we had in the content search web part.

In the highlighted content web part you can add multiple filters today, which are then joined with an OR. This is useful for many scenarios, but often you want to have AND to limit results instead. For example all sites with a specific title, and not all sites OR all items with a specific title.

The above scenario is one I just looked at, and I didn’t want to roll my own web part. Elio Struyf has a PnP sample search web part, but it doesn’t support the same visuals – and I’ll probably end up modifying this in the end ;) But that’s not for this post.

I decided to dig into the properties of the highlighted content web part, and turns out it has a property named advancedQueryText, which is the query template. This property is not included in the UI, but using for example PnP PowerShell you can set this.

The below JSON has a couple of modifications. I have added SiteLogo as an extra managed property to use when showing the result preview, and I have added KQL in the advancedQueryText property.

image

You can download the properties file from my GitHub repo and modify as needed: https://github.com/wobba/RandomFiles/blob/master/searchprops.json

The below PnP powershell creates a new page, and adds a web part with the properties specified.

$pageName = "Awesome"
Connect-PnPOnline -Url https://contoso.sharepoint.com/sites/awesome
Add-PnPClientSidePage -Name $pageName
$searchProps = Get-Content -Path .\searchprops.json -Raw
Add-PnPClientSideWebPart -Page $pageName -DefaultWebPartType ContentRollup -WebPartProperties $searchProps

The caveat is of course that if you edit the web part properties in the UI, everything breaks ;) Which means this is not 100% production ready yet. Hopefully the advancedQueryText property will make it’s way to the UI soon.

References: