I'm trying to pull the Product ID for the product being viewed in order to pass that ID into TrustPilot's widget to display reviews for that product.
I've tried creating a Snippet with this code:
global $product;
$id = $product->get_id()
But I got an error and - I'll be honest - I don't really understand what I was doing! I've been browsing for solutions for most of the day, so I'm hoping someone might be kind enough to help!
As mentioned, the aim is to be able to populate the data-sku="xxxxxxxx"
field in a TrustPilot "TrustBox" - a javascript tool that pulls & presents reviews from trustpilot. The ID will need to be updated in the HTML for the element, I think.
The whole of the TrustPilot code is shown below:
Add this to Header
<!-- TrustBox script -->
<script type="text/javascript" src="//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js" async></script>
<!-- End TrustBox script -->
Add this to body, where you want the widget to appear
<!-- TrustBox widget - Product Reviews SEO -->
<div class="trustpilot-widget" data-locale="en-GB" data-template-id="5717796816f630043868e2e8" data-businessunit-id="5d472f87ff988700011c73b8" data-style-height="700px" data-style-width="100%" data-theme="light" data-sku="487" data-name="10 Plantshake Pack" data-review-languages="en">
<a href="https://uk.trustpilot.com/review/foga.co" target="_blank" rel="noopener">Trustpilot</a>
</div>
<!-- End TrustBox widget -->
Updated
To get the product ID in single product pages, you can use: $product_id = get_the_ID();
To be sure to get the product object in single product pages, you can use:
$product = wc_get_product( get_the_ID() );
Or even better:
global $product;
if ( ! is_a( $product, 'WC_Product' ) ) {
$product = wc_get_product( get_the_ID() );
}
Now you can use a hooked function, to insert all the related code in single product pages. Your javscript will be populated dynamically with the product name and sku:
add_action('woocommerce_before_single_product', 'action_before_single_product', 5 );
function action_before_single_product(){
global $product;
$id = $product->get_id(); // Product Id
$sku = $product->get_sku(); // Product sku
$name = $product->get_name(); // Product name
?>
<!-- TrustBox widget - Product Reviews SEO -->
<div class="trustpilot-widget" data-locale="en-GB" data-template-id="5717796816f630043868e2e8" data-businessunit-id="5d472f87ff988700011c73b8" data-style-height="700px" data-style-width="100%" data-theme="light" data-sku="<?php echo $sku; ?>" data-name="<?php echo $name; ?>" data-review-languages="en">
<a href="https://uk.trustpilot.com/review/foga.co" target="_blank" rel="noopener">Trustpilot</a>
</div>
<!-- End TrustBox widget -->
<?php
}
Code goes in functions.php file of the active child theme (or active theme). It should work.