Halloween Sale 15% off Ends in See the plans
PHP

Unit Price Display (Price per kg, litre or item)

Shows a comparison price such as "4.50 / kg" under the product price, calculated from a unit quantity you enter on each product.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'woocommerce_product_options_pricing', function () {
    global $product_object;

    $get = function ( $key ) use ( $product_object ) {
        return $product_object instanceof WC_Product ? $product_object->get_meta( $key ) : '';
    };

    woocommerce_wp_text_input( array( 'id' => '_wpide_unit_amount', 'label' => 'Pack contents', 'data_type' => 'decimal', 'description' => 'For example 0.5 for 500 g.', 'desc_tip' => true, 'value' => $get( '_wpide_unit_amount' ) ) );
    woocommerce_wp_text_input( array( 'id' => '_wpide_unit_label', 'label' => 'Unit', 'placeholder' => 'kg', 'value' => $get( '_wpide_unit_label' ) ) );
} );

add_action( 'woocommerce_admin_process_product_object', function ( $product ) {
    // phpcs:disable WordPress.Security.NonceVerification -- WooCommerce verifies the product save nonce.
    if ( isset( $_POST['_wpide_unit_amount'], $_POST['_wpide_unit_label'] ) ) {
        $product->update_meta_data( '_wpide_unit_amount', wc_format_decimal( wp_unslash( $_POST['_wpide_unit_amount'] ) ) );
        $product->update_meta_data( '_wpide_unit_label', sanitize_text_field( wp_unslash( $_POST['_wpide_unit_label'] ) ) );
    }
    // phpcs:enable
} );

add_filter( 'woocommerce_get_price_html', function ( $html, $product ) {
    $amount = (float) $product->get_meta( '_wpide_unit_amount' );
    $label  = $product->get_meta( '_wpide_unit_label' );

    if ( $amount <= 0 || '' === $label || '' === $product->get_price() || $product->is_type( 'variable' ) ) {
        return $html;
    }

    $unit = wc_get_price_to_display( $product ) / $amount;

    return $html . sprintf( '<br><small class="wpide-unit-price">%s / %s</small>', wc_price( $unit ), esc_html( $label ) );
}, 20, 2 );

Notes

Enter the pack contents (for example 0.5 for 500 g) and the unit on each product's General tab; products without them are unchanged.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.