skip to Main Content

I’m using the code below in my theme’s functions.php file to be able to output the Product SKU in various places all over my templates with [woo_sku] shortcode. While this works fine, I can’t access the template editor (Elementor) without uncommenting the function, as there is no product context in the template and the error prevents the editor from loading.

Is there a way to catch the error and return an empty value when not in a product context?

function display_woo_sku() {
    global $product;
    return $product->get_sku();
}
add_shortcode( 'woo_sku', 'display_woo_sku' );

2

Answers


  1. Chosen as BEST ANSWER

    I tried the below code now, it appears to work (though Loic's code above seemed to make more sense, imho :)

    function display_woo_sku() { 
        if ( ! is_product() ) {
            return 'no SKU';
        }
        global $product; 
        return $product->get_sku(); 
        } 
    add_shortcode( 'woo_sku', 'display_woo_sku' );
    

  2. Ah, @LoicTheAztec, there was just a typo in your solution: method_exists with an s:

    function display_woo_sku() {
        global $product;
        
        if( is_a( $product, 'WC_Product' ) && method_exists( $product, 'get_sku' ) ) {
            return $product->get_sku();
        } else {
            return  'no SKU';
        }
    }
    add_shortcode( 'woo_sku', 'display_woo_sku' );
    

    Thanx a lot!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search