Using a shortcode with global $product multiple times within a WooCommerce product page


I’m trying to create shortcode for the SKU so I can use it to prefill a mailto link for enquiries from the product page. This means I need to use the shortcode twice on the same page (to put it in the email title and body).

Using the following code works perfectly if the [sv_sku] shortcode is only used once in a page.

function skyverge_echo_wc_sku() {
 global $product;
 return $product->get_sku();
add_shortcode( 'sv_sku', 'skyverge_echo_wc_sku' );

However, if I try and use the shortcode twice on the page, then I get a blank screen and in the error logs it says there was an error on the return line:

PHP message: PHP Fatal error: Uncaught Error: Call to a member
function get_sku() on null

I’m at a loss here. Is it to do with calling global $product multiple times? Or am I missing something more fundamental?


Tim 1 year 2021-07-28T05:33:36-05:00 0 Answers 0 views 0

Leave an answer