Search code examples
phpwordpresswoocommercehook-woocommerce

Enable back price suffix to a function that display customized product prices in WooCommerce


I am using "Enable sale price for logged users and regular price for unlogged users in Woocommerce" first function code, that hides sales price. That way I can use sales price and regular price for logged in vs none logged in users and it Works like a charm.

The Problem I have is that it also kills the woocommerce_price_suffix field from the settings and I want to include it in my function, but don't know how.


Solution

  • The following will add back the price suffix:

    //Variable and simple product displayed prices (removing sale price range)
    add_filter( 'woocommerce_get_price_html', 'custom_get_price_html', 20, 2 );
    function custom_get_price_html( $price, $product ) {
        if( $product->is_type('variable') )
        {
            if( is_user_logged_in() ){
                $price_min  = wc_get_price_to_display( $product, array( 'price' => $product->get_variation_sale_price('min') ) );
                $price_max  = wc_get_price_to_display( $product, array( 'price' => $product->get_variation_sale_price('max') ) );
            } else {
                $price_min  = wc_get_price_to_display( $product, array( 'price' => $product->get_variation_regular_price('min') ) );
                $price_max  = wc_get_price_to_display( $product, array( 'price' => $product->get_variation_regular_price('max') ) );
            }
    
            if( $price_min != $price_max ){
                if( $price_min == 0 && $price_max > 0 )
                    $price = wc_price( $price_max );
                elseif( $price_min > 0 && $price_max == 0 )
                    $price = wc_price( $price_min );
                else
                    $price = wc_format_price_range( $price_min, $price_max );
            } else {
                if( $price_min > 0 )
                    $price = wc_price( $price_min);
            }
            $price .= $product->get_price_suffix()
        }
        elseif( $product->is_type('simple') )
        {
            if( is_user_logged_in() )
                $active_price = wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) );
            else
                $active_price = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );
    
            if( $active_price > 0 )
                $price = wc_price($active_price) . $product->get_price_suffix();
        }
        return $price;
    }
    

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