WP SITES

3086 Coded Tutorials & 291 Plugins

Reposition The Price Using WooCommerce Get Price HTML

By default, WC displays the sale price inline with the regular price as you can see in the image on the left.

This code repositions the sale price below the regular price on both variable and simple products.

add_filter( 'woocommerce_get_price_html', 'wpsites_reposition_sale_price_html', 10, 2 );
function wpsites_reposition_sale_price_html( $price, $product ) {

    if ( $product->is_on_sale() ) {
    
        if ( $product->is_type('variable') ) {
            // For variable products, get min and max prices
            $regular_price_min = $product->get_variation_regular_price('min', true);
            $regular_price_max = $product->get_variation_regular_price('max', true);
            $sale_price_min    = $product->get_variation_sale_price('min', true);
            $sale_price_max    = $product->get_variation_sale_price('max', true);

            if ( $regular_price_min !== $sale_price_min || $regular_price_max !== $sale_price_max ) {
                // Display price range for variable products
                $price = '<del>' . wc_price( $regular_price_min ) . '</del> <br> <ins>' . wc_price( $sale_price_min ) . '</ins>';
            }
        } else {
            // For simple products, just get regular and sale prices
            $regular_price = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );
            $sale_price = wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) );

            $price = '<del>' . wc_price( $regular_price ) . '</del> <br> <ins>' . wc_price( $sale_price ) . '</ins>';
        }
    } else {
        // Display regular price when not on sale
        $regular_price_display = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );
        $price = wc_price( $regular_price_display );
    }

    return $price;
}

Using a code editor and FTP, paste the code at the end of your child themes functions file.

Leave a Reply

New Plugins