All snippets

WooCommerce product dimensions shortcode

Display product length, width and height with the WooCommerce unit. The shortcode checks complete dimensions and public product access.

[mmh_product_dimensions] displays length × width × height. It returns nothing if a dimension is missing or non-positive, preventing two numbers from looking like a complete three-dimensional measurement.

Installation and code

Add one language version to a PHP snippet set to run everywhere, or to your child theme’s functions.php. Test on a staging copy first. The example omits the opening PHP tag. Do not activate both language versions together.

add_shortcode( 'mmh_product_dimensions', function ( $atts ) {
    if ( ! function_exists( 'wc_get_product' ) ) { return ''; }
    $atts = shortcode_atts( array( 'id' => '' ), $atts, 'mmh_product_dimensions' );
    if ( '' !== $atts['id'] ) {
        if ( ! preg_match( '/^[1-9][0-9]*$/D', (string) $atts['id'] ) ) { return ''; }
        $item = wc_get_product( (int) $atts['id'] );
    } else {
        global $product;
        $item = $product instanceof WC_Product ? $product : wc_get_product( get_the_ID() );
    }
    if ( ! $item instanceof WC_Product || 'publish' !== $item->get_status() ) { return ''; }
    $public_id = $item->is_type( 'variation' ) ? $item->get_parent_id() : $item->get_id();
    if ( 'publish' !== get_post_status( $public_id ) || post_password_required( $public_id ) ) { return ''; }
    $dimensions = $item->get_dimensions( false );
    foreach ( array( 'length', 'width', 'height' ) as $key ) {
        if ( ! isset( $dimensions[$key] ) || (float) $dimensions[$key] <= 0 ) { return ''; }
    }
    $text = html_entity_decode( wp_strip_all_tags( wc_format_dimensions( $dimensions ) ), ENT_QUOTES, 'UTF-8' );
    return '<span class="mmh-product-dimensions">' . esc_html( $text ) . '</span>';
} );

Usage and checks

Place the shortcode in a Shortcode block on the product page. Elsewhere, use [mmh_product_dimensions id="123"] with the real product ID. Dimensions 10, 20 and 30 with unit cm should produce 10 × 20 × 30 cm. Also try a missing height, zero width, draft and password-protected product.

Limitations and removal

Values come from WooCommerce shipping dimension fields. Do not label them installation dimensions if they describe a parcel. An explicit variation ID works, but selecting a variation does not update this text dynamically. A variable parent uses its own values. After disabling the snippet, remove shortcode instances from pages to avoid displaying their literal text.

Disable the snippet to remove its output. The examples use fixed language strings; connect them to your translation system for a multilingual store. PHP behaviour was checked on WordPress 7.1.5, WooCommerce 11.3.1 and PHP 8.4.23; verify appearance in your own theme or email template.

Organise other specifications using product tabs.

Technical reference