Установите цены на товары, основываясь на диапазоне их размеров (площади) в woocommerce

Я использую WordPress и WooCommerce для веб-сайта электронной коммерции.
Я хотел бы динамически рассчитать продукт по его площади (высота х ширина)

Таким образом, цена продукта будет основываться условно на диапазонах области, таких как:

  • если область между 1 (Кв) до 5 (Кв) цена 5 $
  • если область между 6 (Кв) до 10 (Кв) цена 6 $

Любая помощь будет оценена.

1

Решение

Попробуйте следующий пример кода, который будет автоматически рассчитывать цену продукта на основе его площади когда продукт сохраняется в бэкэнде. Возможно, вам придется внести некоторые коррективы в расчет площади на основе настроек вашей единицы измерения …

Код:

add_action( 'save_post', 'calculate_product_price_based_on_area', 20, 3 );
function calculate_product_price_based_on_area( $post_id, $post, $update ) {

if ( $post->post_type != 'product') return; // Only products

// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;

// Check the user's permissions.
if ( ! current_user_can( 'edit_product', $post_id ) )
return $post_id;

// Product width and height
$width  = isset($_POST['_width'])  ? (float) $_POST['_width']  : 0;
$height = isset($_POST['_height']) ? (float) $_POST['_height'] : 0;

if( $width > 0 && $height > 0 ){
// Area calculation from product width and height
$area = $width * $height;

// Define the price conditionally based on area
if( $area > 0 && $area <= 5 ){
$price = 5;
} elseif( $area > 5 && $area <= 10 ){
$price = 6;
}

// Update the calculated product price
if( isset($price) && $price > 0 ){
// if product is not on sale
if( $_POST['_sale_price'] != '' ){
// Update active price
update_post_meta( $post_id, '_price', $price );
}
// Update regular price
update_post_meta( $post_id, '_regular_price', $price );
wc_delete_product_transients( $post_id ); // Update product cache
}
}
}

Код помещается в файл function.php вашей активной дочерней темы (или активной темы). Проверено и работает.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector