Skip to main content

Example : Add Metafield Data to PLP

JS Code:

var __fast_options  = { with_product_attributes: true};

/* get all products to loop on */
function getProductElements(element) {
return [...element.querySelectorAll(`.fs-results-product-card`)];
}



function Getattributevalue(att,name) {
if ( typeof(att) !== "undefined" && att !== null ) {
for (let key in att) {
if (att[key][0] === name){
return att[key][1][0];
}
}
}

return "";
}


function addlimitedtimeLabel(productElement, value) {
if (productElement.querySelectorAll(`.my-limitedtime-labels`).length === 0) {
productElement.querySelector(".info-container").insertAdjacentHTML('beforeend', `<div class="my-limitedtime-labels">${value}</div>`);
}
}


function hooks() {
window.SerpOptions.registerHook("serp-product-grid", ({products, element}) => {

for (const productElement of getProductElements(element)) {
/* get product data */
const productID = productElement.dataset.productId;
const data = products[productID];

if ( typeof(data) !== "undefined" && data !== null ) {

const tags = data.attributes;

/* additional metafield */
var $limitedtime = Getattributevalue(data.attributes,"Custom.limited time price tag");

if ($limitedtime.length > 0) {
addlimitedtimeLabel (productElement,$limitedtime);
}


}

}
});
}

// execution here
if (window.SerpOptions) {
hooks();
} else {
window.addEventListener('fast-serp-ready', function () {
hooks();
});
}

You need to add the metafield name into the dashboard:

image