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?
Advertisement
Answer
You can use the following simple code snippet, to display product dimensions via a shortcode:
add_shortcode( 'product_dimensions', 'display_product_dimensions' ); function display_product_dimensions( $atts ){ // Extract shortcode attributes extract( shortcode_atts( array( 'id' => '', ), $atts, 'product_dimensions' ) ); if( $id == '' ) { global $product; if( ! is_a($product, 'WC_Product') ) { $product = wc_get_product( get_the_id() ); } } return method_exists( $product, 'get_dimensions' ) ? wc_format_dimensions($product->get_dimensions(false)) : ''; }
Code goes in functions.php file of the active child theme (or active theme). it should works.
USAGE:
- On WooCommerce product single page:
[product_dimensions]
- Anywhere with a defined Id (for example product Id 35):
[product_dimensions id="35"]