Добавление процента скидки к переменным продуктам в продаже

Я пытаюсь добавить процент скидки в сторону цены на сайте, который использует WooCommerce.

Я применил этот скрипт для стандартной цены и цены продажи:

// Add save percentage next to sale item prices.
add_filter( 'woocommerce_get_price_html', 'adventure_tours_sales_price', 10, 2 );
function adventure_tours_sales_price( $price, $product ){
  $percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
  return $price . sprintf( __(' Save %s', 'woocommerce' ), $percentage . '%' );
}

Сценарий выше работает.

В front-end у меня есть процентная цена.

Теперь я хочу применить тот же сценарий к цене варианта продукта.

Я проверил вариант варианта продукта и попробовал что-то вроде этого:

// Add save percentage next to sale item prices.
add_filter( 'woocommerce_get_price_html', 'adventure_tours_sales_price', 10, 2 );
function adventure_tours_sales_price( $price, $product ){
  if( $product->is_type( 'variable' ) ) {
    $percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
    return $price . sprintf( __(' Save %s', 'woocommerce' ), $percentage . '%' );
  }else{
    $percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
    return $price . sprintf( __(' Save %s', 'woocommerce' ), $percentage . '%' );
  }
}

Но это не работает, процент не применяется к цене.

Ни в передней части.

1 ответ

Решение

Обновление для версий WooCommerce 3+ | Замена устаревших крючков

  • Замените "woocommerce_variable_sale_price_html" на "woocommerce_variable_get_price_html"
  • Замените "woocommerce_sale_price_html" на "woocommerce_get_price_html"

(Спасибо Нитину)


Для переменных продуктов сложнее, так как у вас есть 2 разных местоположения с ценами, первое отображает минимальную и максимальную цену (если у вас есть несколько вариантов), а второе отображает цену из выбранных вариантов. Я сильно изменил ваш оригинальный код.

Вот правильный код для отображения, что пользовательские динамические метки окружают дисконтированные проценты:

add_filter('woocommerce_variation_sale_price_html','adventure_tours_sales_price', 10, 2 );
add_filter('woocommerce_sale_price_html','adventure_tours_sales_price', 10, 2 );
function adventure_tours_sales_price( $price, $product ){

    // Variables initialisation
    $regular_price = $product->regular_price;
    $sale_price    = $product->sale_price;
    $save_text     = __('Save', 'woocommerce') . ' ';

    if(!empty($sale_price)) {
        // Percentage calculation
        $percentage = '<span class="save-percent"> ' .$save_text . round( ( ( $regular_price -  $sale_price ) / $regular_price ) * 100 ) . '%</span>';

        $price = '<del class="strike">' . woocommerce_price( $regular_price ) . '</del>
        <ins class="highlight">' . woocommerce_price( $sale_price )  . $percentage . '</ins>';
    } else {
        $price = '<ins class="highlight">'.woocommerce_price( $regular_price ).'</ins>';
    }
    return $price;
}

add_filter('woocommerce_variable_sale_price_html', 'adventure_tours_sales_min_max_prices', 20, 2);
function adventure_tours_sales_min_max_prices( $price, $product) {

    // Variables initialisation
    $variation_min_reg_price = $product->get_variation_regular_price('min', true);
    $variation_max_reg_price = $product->get_variation_regular_price('max', true);
    $variation_min_sale_price = $product->get_variation_sale_price('min', true);
    $variation_max_sale_price = $product->get_variation_sale_price('max', true);
    $percentage_min = '';
    $percentage_max = '';
    $save_text     = __('Save', 'woocommerce') . ' ';

    // Percentage calculations
    if($variation_min_reg_price != $variation_min_sale_price)
        $percentage_min = '<span class="save-percent-min"> (' .$save_text . round( ( ( $variation_min_reg_price -  $variation_min_sale_price ) / $variation_min_reg_price ) * 100 ) . '%)</span>';
    if($variation_max_reg_price != $variation_max_sale_price)
        $percentage_max = '<span class="save-percent-max"> (' .$save_text . round( ( ( $variation_max_reg_price -  $variation_max_sale_price ) / $variation_max_reg_price ) * 100 ) . '%)</span>';

    if (($variation_min_reg_price != $variation_min_sale_price) || ($variation_max_reg_price != $variation_max_sale_price)) {
        $price = '<del class="strike">' . woocommerce_price($variation_min_reg_price) . '-' . woocommerce_price($variation_max_reg_price) .  '</del>
        <ins class="highlight">' . woocommerce_price($variation_min_sale_price) . $percentage_min . ' - ' . woocommerce_price($variation_max_sale_price) . $percentage_max . '</ins>';
    }
    return $price;
}

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

Протестировано и работает на Woocommerce версии 2.6.x (также работает для версии 3+ с заменой хуков).

Вот что вы получите (скриншоты с моего тестового сервера):

введите описание изображения здесь


Связанные ответы:

Другие вопросы по тегам