نمایش کمترین مقدار وزن محصول ووکامرس
با استفاده از این کد میتوان کمترین وزن ثبتشده برای یک محصول ووکامرس را با شورتکد [min_weight] نمایش داد.
در محصولات ساده، وزن خود محصول بررسی میشود و در محصولات متغیر، وزن تمام ورییشنها بررسی شده و کمترین وزن انتخاب میشود. مقدار وزن با سه رقم اعشار و اعداد فارسی نمایش داده شده و واحد g نیز در کنار آن قرار میگیرد.
همچنین وزن بهصورت خودکار روی تصویر محصولات در صفحه آرشیو فروشگاه نمایش داده میشود.
شورتکد:
[min_weight]
<?php
function show_min_weight_pa_weight_shortcode($atts) {
global $product;
if (!$product) {
return '';
}
$weights = array();
$to_persian_number = function($number_string) {
return str_replace(
['0','1','2','3','4','5','6','7','8','9','.'],
['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹','٫'],
$number_string
);
};
if ($product->is_type('simple')) {
$weight = $product->get_weight();
if (!empty($weight)) {
$weights[] = $weight;
}
}
if ($product->is_type('variable')) {
$variation_ids = $product->get_children();
foreach ($variation_ids as $variation_id) {
$variation = wc_get_product($variation_id);
if (!$variation) continue;
$var_weight = $variation->get_weight();
if (!empty($var_weight)) {
$weights[] = $var_weight;
}
}
}
if (empty($weights)) return '';
$min_weight = min(array_map('floatval', $weights));
$formatted_weight = number_format($min_weight, 3, '.', '');
$formatted_weight = $to_persian_number($formatted_weight);
return '<span class="custom-min-weight" style="font-size:12px; color:#888888; direction:ltr; display:inline-block;">'
. esc_html($formatted_weight)
. ' g</span>';
}
add_shortcode('min_weight', 'show_min_weight_pa_weight_shortcode');
// نمایش روی تصویر محصول در آرشیو
function show_min_weight_on_archive_image() {
global $product;
if (!$product) return;
$weight = do_shortcode('[min_weight]');
if (empty($weight)) return;
echo '<div style="position:absolute; bottom:8px; left:5px; z-index:10;">' . $weight . '</div>';
}
add_action('woocommerce_before_shop_loop_item_title', 'show_min_weight_on_archive_image', 20);