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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.