Chia sẻ code thêm “Giảm x%” vào sau giá của Woo trong chi tiết sản phẩm

Cập nhật lần cuối 19/12/2025 by trong WordPress vào 19/12/2025 có 51 Views

Code thêm vào wp-content/themes/{your-theme}/functions.php của theme nhé

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
add_action( 'woocommerce_single_product_summary', 'devvn_single_price_with_sale_percent', 10 );
function devvn_single_price_with_sale_percent() {
    global $product;

    if ( ! $product ) return;

    $html = '';

    if ( $product->is_on_sale() ) {

        $regular = (float) $product->get_regular_price();
        $sale    = (float) $product->get_sale_price();

        if ( $regular > 0 && $sale > 0 ) {
            $percent = round( ( ( $regular - $sale ) / $regular ) * 100 );

            $html .= '<span class="devvn_price sale_amount">';
            $html .= '(Giảm ' . $percent . '%)';
            $html .= '</span> ';
        }
    }

    echo '<p class="price">' . $html . $product->get_price_html() . '</p>';
}

add_filter( 'woocommerce_available_variation', 'devvn_add_sale_percent_to_variation_price', 10, 3 );
function devvn_add_sale_percent_to_variation_price( $data, $product, $variation ) {

    if ( $variation->is_on_sale() ) {

        $regular = (float) $variation->get_regular_price();
        $sale    = (float) $variation->get_sale_price();

        if ( $regular > 0 && $sale > 0 && !empty($data['price_html'])) {
            $percent = round( ( ( $regular - $sale ) / $regular ) * 100 );

            $data['price_html'] =
                '<span class="devvn_price sale_amount">(Giảm ' . $percent . '%)</span> '
                . $data['price_html'];
        }
    }

    return $data;
}

Code css cho đẹp. Thêm vào bất kỳ chỗ nào cho phép chèn css hoặc Giao diện> Tùy biến > Css bổ sung

span.devvn_price.sale_amount {
    font-size: 14px;
    font-weight: 400;
    letter-spacing: normal;
}
.woocommerce div.product div.summary > p.price {
    display: flex;
}
.woocommerce div.product div.summary > p.price span.devvn_price.sale_amount {
    order: 3;
    margin-left: 10px;
}

Mong rằng chia sẻ nhỏ này giúp ích được cho bạn!

Để duy trì blog nên mình có làm aff cho 1 số bên hosting. Nhưng dù aff mình cũng chọn 1 số nhà cung cấp uy tín về chất lượng và support nên các bạn cứ yên tâm nhé.

Nếu có mua hosting mà có trong list dưới đây các bạn click vào link trước khi mua để ủng hộ mình nhé. Mình cảm ơn nhiều

5/5 - (1 vote)
  • Bình luận
Sản phẩm nổi bật của Toản
x