Search code examples
objectwoocommercemethodshook-woocommercewordpress-shortcode

WooCommerce Custom shortode : Avoid problems with Elementor editor


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' );

Solution

  • To avoid that problem, what you can do is:

    • First check that $product is a WC_Product Object using is_a() PHP function,
    • Then also check that the get_sku() method exist for the WC_Product object using method_exists() PHP function.

    You will use both of them in an IF statement like:

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

    It should better work now.