php - Display custom prefix with price per meter on WooCommerce products

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
Answer
Solution:
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;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function store() on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.