Отобразить цену вариации по умолчанию и сумму экономии на Woocommerce 3 - PullRequest
0 голосов
/ 08 мая 2018

Мне нужно отобразить цену изменения по умолчанию и с обычной ценой и суммой экономии на моей домашней странице и странице категории Woocommerce

Я нашел следующий код по этой ссылке ответ Показать самую низкую цену и процент со скидкой в ​​WooCommerce

add_filter( 'woocommerce_get_price_html', 'custom_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'custom_price_format', 10, 2 );
function custom_price_format( $price, $product ) {

    // Main Price
    $regular_price = $product->is_type('variable') ? $product->get_variation_regular_price( 'min', true ) : $product->get_regular_price();
    $sale_price = $product->is_type('variable') ? $product->get_variation_sale_price( 'min', true ) : $product->get_sale_price();


    if ( $regular_price !== $sale_price && $product->is_on_sale()) {
    // Percentage calculation and text
    $percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
    $percentage_txt = __(' Save', 'woocommerce' ).' '.$percentage;

    $price = '<del>' . wc_price($regular_price) . '</del> <ins>' . wc_price($sale_price) . $percentage_txt . '</ins>';
    }
    return $price;
}

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

Заранее спасибо.

1 Ответ

0 голосов
/ 08 мая 2018

Попробуйте следующее, где мы сначала ищем переменные продукты, цены вариаций по умолчанию.

add_filter( 'woocommerce_get_price_html', 'custom_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'custom_price_format', 10, 2 );
function custom_price_format( $price, $product ) {

    // 1. Variable products
    if( $product->is_type('variable') ){

        // Searching for the default variation
        $default_attributes = $product->get_default_attributes();
        // Loop through available variations
        foreach($product->get_available_variations() as $variation){
            $found = true; // Initializing
            // Loop through variation attributes
            foreach( $variation['attributes'] as $key => $value ){
                $taxonomy = str_replace( 'attribute_', '', $key );
                // Searching for a matching variation as default
                if( isset($default_attributes[$taxonomy]) && $default_attributes[$taxonomy] != $value ){
                    $found = false;
                    break;
                }
            }
            // When it's found we set it and we stop the main loop
            if( $found ) {
                $default_variaton = $variation;
                break;
            } // If not we continue
            else {
                continue;
            }
        }
        // Get the default variation prices or if not set the variable product min prices
        $regular_price = isset($default_variaton) ? $default_variaton['display_price']: $product->get_variation_regular_price( 'min', true );
        $sale_price = isset($default_variaton) ? $default_variaton['display_regular_price']: $product->get_variation_sale_price( 'min', true );
    }
    // 2. Other products types
    else {
        $regular_price = $product->get_regular_price();
        $sale_price    = $product->get_sale_price();
    }

    // Formatting the price
    if ( $regular_price !== $sale_price && $product->is_on_sale()) {
        // Percentage calculation and text
        $percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
        $percentage_txt = __(' Save', 'woocommerce' ).' '.$percentage;

        $price = '<del>' . wc_price($regular_price) . '</del> <ins>' . wc_price($sale_price) . $percentage_txt . '</ins>';
    }
    return $price;
}

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

Теперь этот код никогда не получит выбранную цену варианта, поскольку это живое событие в клиентском браузере, которое намного сложнее обрабатывать (в этом случае потребуется Php и Jquery).

Связанный связанный ответ: Отображение самой низкой цены вариации и дисконтированного процента в WooCommerce

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...