phpfunctionwoocommerce

Woocommerce: Add text to price in cart but not to Related Products


I've added the text "kg*" after the price on the product page. However, it also adds the additional text to the price of the Related Products below. How do I exclude the price being added to the Related Products? I want to add the text only to the price of the product.

add_filter( 'woocommerce_get_price_html', 'hellblau_kg_nach_preis', 100, 2  );
function hellblau_kg_nach_preis($price){
    if( is_single() ) { 
        global $product;
        $weight = $product->get_weight();    
        return $price . ' / ' . $weight . ' kg*';
    }
    return $price;
}

I've tried several things like if( is_single() && ! RELATED-PRODUCTS ) without success.


Solution

  • To prepend a text to single product price, but not to related products, use the following:

    add_filter( 'woocommerce_get_price_html', 'hellblau_kg_nach_preis', 100, 2  );
    function hellblau_kg_nach_preis( $price_html, $product ){
        global $woocommerce_loop;
    
        // Only on single product pages and not on related products
        if( is_product() && $woocommerce_loop['name'] !== 'related' ) { 
    
            $weight = $product->get_weight(); 
            if ( $weight > 0 ) {
                $price_html .= ' / ' . $weight . ' kg*';
            }
        }
        return $price_html;
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    Related: Set Discounted Price for Related Product on Product Page