I have this code that works for simple product type but not for variable products in WooCommerce:
add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
global $product;
return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );
}
How can I make it work for both simple and variable products?
3
Answers
You need the Variation ID to get the SKU of Variable Product.
If you pass the Variation ID in the below Function, then you can get its SKU.
The below code can be used to get the variations of a product. Then lopp the result to get the variation ID and then use that variation ID in the above code to get the result.
You need to use
get_available_variations();
.Reference:
get_available_variations()
~ https://docs.woocommerce.com/wc-apidocs/class-WC_Product_Variable.htmlTo make it work also for variable products and their variations, it requires Javascript (jQuery) to get the selected variation SKU for variable products.
Try the following that works for simple an variable product types, displaying the selected variation SKU for variable products:
Code goes in functions.php file of your active child theme (or active theme). Tested and work.