Reputation: 65
I'm using this code to add text below the price of my products
function cw_change_product_price_display( $price ) {
$price .= ' <span class="unidad">por unidad</span>';
return $price;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );
But I need to display the following text: Price per meter is: and this formula:
$product->get_price()/$product->get_length() . get_woocommerce_currency_symbol();
Product price divided product length, can't get it to work without causing a error in the site.
Also, Is there any way to make this code apply to only certain products? As there are many that are sold per unit
Upvotes: 2
Views: 522
Reputation: 254192
You can use it this way for your simple products:
add_filter( 'woocommerce_get_price_html', 'custom_product_price_display', 10, 2 );
add_filter( 'woocommerce_cart_item_price', 'custom_product_price_display', 10, 2 );
function custom_product_price_display( $price, $product ) {
if( ! is_a( $product, 'WC_Product' ) ) {
$product = $product['data'];
}
// Price per meter prefixed
if( $product->is_type('simple') && $product->get_length() ) {
$unit_price_html = wc_price( $product->get_price() / $product->get_length() );
$price .= ' <span class="per-meter">' . __("Price per meter is: ") . $unit_price_html . '</span>';
}
return $price;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
To handle both "the displayed price per meter" and the prefix "per unit", use the following instead:
add_filter( 'woocommerce_get_price_html', 'custom_product_price_display', 10, 2 );
add_filter( 'woocommerce_cart_item_price', 'custom_product_price_display', 10, 2 );
function custom_product_price_display( $price, $product ) {
if( ! is_a( $product, 'WC_Product' ) ) {
$product = $product['data'];
}
// Price per meter prefixed
if( $product->is_type('simple') && $product->get_length() ) {
$unit_price_html = wc_price( $product->get_price() / $product->get_length() );
$price .= ' <span class="per-meter">' . __("Price per meter is: ") . $unit_price_html . '</span>';
}
// Prefix" per unit"
else {
$price .= ' <span class="per-unit">' . __("per unit") . $unit_price_html . '</span>';
}
return $price;
}
Upvotes: 2