Karthik
Karthik

Reputation: 5759

Display product price based on quantity in WooCommerce

How to display Product price based on 12 quantity in woocommerce shop page.

enter image description here

function sv_change_product_html( $price_html, $product ) {
    $unit_price = get_post_meta( $product->id, 'unit_price', true );
    if ( ! empty( $unit_price ) ) {
        $price_html = '<span class="amount">' . wc_price( $unit_price ) . ' inc GST per bottle</span>'; 
    }

    return $price_html;
}

add_filter( 'woocommerce_get_price_html', 'sv_change_product_html', 10, 2 );


function sv_change_product_price_cart( $price, $cart_item, $cart_item_key ) {

      $unit_price = get_post_meta( $cart_item['product_id'], 'unit_price', true );
    if ( ! empty( $unit_price ) ) {
        $price = wc_price( $unit_price ) . ' inc GST per bottle';   
    }
    return $price;

}   

add_filter( 'woocommerce_cart_item_price', 'sv_change_product_price_cart', 10, 3 );

Upvotes: 0

Views: 415

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253921

Your code is a bit outdated since WooCommerce 3 (and your question a bit unclear)… Try the following:

add_filter( 'woocommerce_get_price_html', 'displayed_product_unit_price', 10, 2 );
function displayed_product_unit_price( $price_html, $product ) {
    if ( $unit_price = $product->get_meta( 'unit_price' ) ) {
        $price_html  = '<span class="amount">' . wc_price( floatval( $unit_price ) ) . ' ' . __( "inc GST per bottle", "woocommerce") . '</span><br>';
        $price_html .= '<span class="amount">' . wc_price( floatval( $unit_price ) * 12 ) . ' ' . __( "inc GST per 12-bottles", "woocommerce") . '</span>';
    }
    return $price_html;
}



add_filter( 'woocommerce_cart_item_price', 'displayed_cart_item_unit_price', 10, 3 );
function displayed_cart_item_unit_price( $price, $cart_item, $cart_item_key ) {
    if ( $unit_price = $cart_item['data']->get_meta( 'unit_price' ) ) {
        $price = wc_price( floatval( $unit_price ) ) . ' ' . __( "inc GST per bottle", "woocommerce");
    }
    return $price;
} 

Code goes in function.php file of your active child theme (or active theme). It should works.

enter image description here

Now if the WooCommerce product active price (by default) is based on 12 bottles, you should replace the following line (in the first function):

$price_html .= '<span class="amount">' . wc_price( floatval( $unit_price ) * 12 ) . ' ' . __( "inc GST per 12-bottles", "woocommerce") . '</span>';

by this line:

$price_html .= '<span class="amount">' . wc_price( wc_get_price_to_display( $product ) ) . ' ' . __( "inc GST per 12-bottles", "woocommerce") . '</span>';

Upvotes: 1

Related Questions