I’m using a WordPress shopping theme and it displays the products details (price, colors etc) as json scripts, however I need to display at least the price as text. The developer was not very helpful and my php knowledge is limited to none, so I’m hoping this will be an easy/fast fix for someone here.
This is the part of the script that generates the json:
if(is_array($product['skuAttr'])) {
$str_data['offers'] = [];
foreach ($product['skuAttr'] as $k => $attr) {
$str_data['offers'][] = [
"@type" => "Offer",
"url" => $this_url . '?sku=' . $k,
"priceCurrency" => $product['currency'],
"price" => $attr['_salePrice_nc'],
"priceValidUntil" => date('Y-m-d',
strToTime('today + 30 days')
),
"name" => $itemmeta['name'],
"availability" => $attr['isActivity'] ? "https://schema.org/InStock" : "https://schema.org/OutOfStock",
"itemCondition" => "https://schema.org/NewCondition"
];
$min_saleprice = min($attr['_salePrice_nc']); // that's mine
}
}
…and later on:
<script type="application/ld+json">
<?php echo json_encode($str_data); ?>
</script>
The $min_saleprice was my idea that I later echoed and, of course, it broke the site.
<?php echo $min_saleprice; ?> /// not a chance
So, how to display the _salePrice_nc later in the document?
Thank you.
If it matters, I am using the latest WordPress 5.6.1, PHP 7.2, nGinx and I need this to validate the products on Pinterest, whose scraper is not smart enough to get the price from the script, and I think it must find it in page as plain text.
enter image description here
2
Answers
If you want the lowest value of the price in offers then you can build an array just for that purpose and get the lowest of that.
But you will need to make sure this is outside the loop.
You made two critical errors:
The correct place where you should look for the minimal value is the final array of all offers and it should be done outside the loop. The following code will achieve this:
The
array_column
function extracts all of theprice
values from$str_data['offers']
and thenmin
selects the lowest of them.