John Davidson

php - Display WooCommerce Product Dimensions via a Shortcode

0 comments
Message:


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?



My Answer:
>get_description() );_ }_ } catch (Exception $e) {_ return '';_ }_}_add_shortcode('product_description', 'custom_product_description');_You can modify the code above to display the product dimensions by accessing the product's dimensions data. Here's an example of how you can modify the code to display the product dimensions:

php
function custom_product_dimensions($atts){
global $product;

try {
if( is_a($product, 'WC_Product') ) {
$dimensions = $product->get_dimensions();
$length = isset($dimensions['length']) ? $dimensions['length'] : '';
$width = isset($dimensions['width']) ? $dimensions['width'] : '';
$height = isset($dimensions['height']) ? $dimensions['height'] : '';

$output = '';
if ($length) {
$output .= 'Length: ' . $length . '
';
}
if ($width) {
$output .= 'Width: ' . $width . '
';
}
if ($height) {
$output .= 'Height: ' . $height . '
';
}

return $output;
}
} catch (Exception $e) {
return '';
}
}
add_shortcode('product_dimensions', 'custom_product_dimensions');


You can then use the `[product_dimensions]` shortcode in your custom tab to display the product dimensions. This code will retrieve the product dimensions (length, width, height) and display each one on a separate line.

Rate this post

5 of 5 based on 2755 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us