تبدیل متن تخفیف به «فروش ویژه» در ووکامرس
این کد ظاهر برچسب تخفیف محصولات ووکامرس را تغییر میدهد و بهجای نمایش متن پیشفرض «تخفیف» یا Sale، عبارت «فروش ویژه» را نمایش میدهد.
در کنار عبارت فروش ویژه، درصد تخفیف واقعی محصول نیز بهصورت خودکار محاسبه و نمایش داده میشود. درصد تخفیف بر اساس تفاوت قیمت اصلی و قیمت فروش محاسبه شده و در صورتی که محصول تخفیف نداشته باشد، برچسب نمایش داده نمیشود.
همچنین با استفاده از CSS، ظاهر برچسب شامل رنگ، پسزمینه، فاصله و حالت نمایش آن سفارشی شده است.
<?php
add_action('wp_head', function () {
echo '<style>
.sale-percent{ background:#e74c3c; color:#fff; padding:5px; font-weight:bold; }
.sale-text{ padding:5px; color:#e74c3c!important; font-weight:bold!important; }
.onsale{ background:rgba(231,76,60,.18)!important; display:inline-flex!important; padding:0!important; border-radius:5px!important; overflow:hidden!important; min-width:0!important; min-height:0!important; line-height:1!important; white-space:nowrap!important; inset:auto!important; }
</style>';
});
function vira_get_sale_percent($product) {
if (!$product instanceof WC_Product) {
return 0; }
if (!$product->is_on_sale()) {
return 0; }
$regular_price = (float) $product->get_regular_price();
$sale_price = (float) $product->get_sale_price();
if ($regular_price <= 0 || $sale_price <= 0) {
return 0; }
return round((1 - ($sale_price / $regular_price)) * 100, 2);
}
function vira_format_percent($percent) {
if ($percent <= 0) {
return ''; }
$formatted = rtrim(rtrim(number_format($percent, 2, '.', ''), '0'), '.');
return '<span class="sale-percent">٪'.$formatted.'</span>';
}
// تغییر متن فروش ویژه ووکامرس
add_filter('woocommerce_sale_flash', 'vira_custom_sale_text', 10, 3);
function vira_custom_sale_text($html, $post, $product) {
if (!$product instanceof WC_Product || !$product->is_on_sale()) {
return ''; }
$percent = vira_get_sale_percent($product);
if ($percent <= 0) {
return ''; }
return '<span class="onsale">'
. vira_format_percent($percent) .
'<span class="sale-text">فروش ویژه</span>'
. '</span>';
}