I am creating a custom layout (using Elementor) for a product - what I need is to have the dimensions of a product to display in a custom tab I have created.
Is there a shortcode for product dimensions? (some of the products are variable too if that makes a difference)
I have managed to get some code to display the long description in a shortcode (see below) however I'm not advanced enough to know what to do to get it to display product dimensions (length, width, height - ideally each one on a separate line)
Here is the long description code i found that works...
function custom_product_description($atts){
global $product;
try {
if( is_a($product, 'WC_Product') ) {
return wc_format_content( $product->get_description("shortcode") );
}
return "Product description shortcode run outside of product context";
} catch (Exception $e) {
return "Product description shortcode encountered an exception";
}
}
add_shortcode( 'custom_product_description', 'custom_product_description' );
Does anyone can give me some help to display product dimensions via a shortcode?
You can use the following simple code snippet, to display product dimensions via a shortcode:
add_shortcode( 'product_dimensions', 'display_product_formatted_dimensions' );
function display_product_formatted_dimensions( $atts ) {
// Extract shortcode attributes
extract( shortcode_atts( array(
'id' => get_the_ID(),
), $atts, 'product_dimensions' ) );
$product = wc_get_product( $id );
if( ! $product ) {
return;
} elseif ( $dimensions = $product->get_dimensions(false) ) {
return wc_format_dimensions($dimensions);
}
}
Code goes in functions.php file of your child theme (or in a plugin). It should work in WooCommerce 3 and above.
USAGE:
[product_dimensions]
[product_dimensions id="35"]
echo do_shortcode('[product_dimensions]');
NOTE: It will display nothing if dimensions have not been defined for the product.