How to display the weight of a product anywhere using a shortcode

Sometimes you need to display the weight of a product next to the price, in the description or in a special block, and not just in the default parameter table. WooCommerce doesn't have this option by default, but with this simple snippet you can create your own „shortcode“ to insert anywhere.

How does it work?

Snippet creates a new shortcode [product_weight]. When you put it in the product description or in Elementor (or other builder), the code does the following:

  1. Identifies the product: It finds out which product page you are currently on.
  2. Pulls up the data: It queries the database for a numeric weight value.
  3. It will detect the units: It will look into your WooCommerce settings to see if you are using kg, g or other units.
  4. Displays the result: He connects the number with the unit and neatly writes them out. If the weight is not entered, it will warn you (you can easily change the text in the code).
PHP
function custom_product_weight_shortcode() {
    global $product;

    // Checking if we are actually on the product page
    if ( ! is_a( $product, 'WC_Product' ) ) {
        return '';
    }

    $weight = $product->get_weight();

    // If the product does not have the specified weight
    if ( ! $weight ) {
        return 'The weight of this product is not available.';
    }

    // Returns formatted text with one from WooCommerce settings
    return 'The weight of this product is ' . $weight . ' ' . get_option( 'woocommerce_weight_unit' );
}

// Shortcode registration [product_weight]
add_shortcode( 'product_weight', 'custom_product_weight_shortcode' );

Practical tips

  • Where to insert the shortcode: Just type in the text editor in the product administration [product_weight].
  • Multiple products: This shortcode is designed to work within a „Product Loop“ or on a specific product page. If you put it on a regular static page (e.g. „About Us“), it won't display anything because it won't know which weight to pull.
  • Custom text (line 17): To change the sentence „The weight of this product is...“, just edit the text in the last line of the function before the variable $weight.

Leave a Reply

Your email address will not be published. Required fields are marked *