• Никакой политики на форуме. Иначе - бан!
  • Вопрос без рабочей ссылки на проблему считается риторическим. Без ссылки и скриншота - провокацией!
  • Темы озаглавленные с маленькой буквы или капсом удаляются без предупреждения!

Как на странице товара Woocommerce вывести скидку в деньгах а не в процентах?

Romakod

Новичок
Здравствуйте! Подскажите пожалуйста как вывести на странице товара Woocomerse под ценой скидку выраженную в сумме а не в процентах? к примеру "Скидка 245 руб". Как для простых так и для вариативных товаров! К моему сожалению в коде я дуб. Поэтому прошу прощения у тех кто секёт эту тему.
Без названия (1).png

l50_5ocyulwx_x1v__520b36b6.png
 

joy66

Опытный
Вообще-то "из коробки" woo не умеет сообщать про скидку ни так ,ни эдак )) Просто Перечеркнутая обычная и цена со скидкой. Поэтому надо сначала разобраться что отвечает за вывод инфы про скидку (тема, плагин, просто код взятый на просторах и вставленный в functions темы), а потом думать, как это поменять
 

MacKor

Форумчанин
Код:
function woodmart_product_label() {
    global $product;

    $output = array();

    $product_attributes = woodmart_get_product_attributes_label();
    $percentage_label   = woodmart_get_opt( 'percentage_label' );

    if ( 'small' === woodmart_loop_prop( 'product_hover' ) ) {
        return;
    }

    if ( $product->is_on_sale() ) {

        $percentage = '';
        $not_percentage = '1';

        if ( $product->get_type() == 'variable' && $percentage_label ) {

            $available_variations = $product->get_variation_prices();
            $max_percentage       = 0;

            foreach ( $available_variations['regular_price'] as $key => $regular_price ) {
                $sale_price = $available_variations['sale_price'][ $key ];

                if ( $sale_price < $regular_price ) {
                    if ( $not_percentage == '1' ) {
                        $percentage = $regular_price - $sale_price;
                    } else {
                        $percentage = round( ( ( (float) $regular_price - (float) $sale_price ) / (float) $regular_price ) * 100 );
                    }
                    

                    if ( $percentage > $max_percentage ) {
                        $max_percentage = $percentage;
                    }
                }
            }

            $percentage = $max_percentage;
        } elseif ( ( $product->get_type() == 'simple' || $product->get_type() == 'external' || $product->get_type() == 'variation' ) && $percentage_label ) {
            if ( $not_percentage == '1' ) {
                $percentage = $product->get_regular_price() - $product->get_sale_price();
            } else {
                $percentage = round( ( ( (float) $product->get_regular_price() - (float) $product->get_sale_price() ) / (float) $product->get_regular_price() ) * 100 );
            }
            
        }

        if ( $percentage ) {
            if ( $not_percentage == '1' ) {
                $output[] = '<span class="onsale product-label">-' . $percentage . ' ₽</span>';
            } else {
                $output[] = '<span class="onsale product-label">' . sprintf( _x( '-%d%%', 'sale percentage', 'woodmart' ), $percentage ) . '</span>';
            }
            
        } else {
            $output[] = '<span class="onsale product-label">' . esc_html__( 'Sale', 'woodmart' ) . '</span>';
        }
        
    }

    if ( ! $product->is_in_stock() && 'thumbnail' === woodmart_get_opt( 'stock_status_position', 'thumbnail' ) ) {
        $output[] = '<span class="out-of-stock product-label">' . esc_html__( 'Sold out', 'woodmart' ) . '</span>';
    }

    if ( $product->is_featured() && woodmart_get_opt( 'hot_label' ) ) {
        $output[] = '<span class="featured product-label">' . esc_html__( 'Hot', 'woodmart' ) . '</span>';
    }

    if ( woodmart_get_opt( 'new_label' ) && woodmart_is_new_label_needed( get_the_ID() ) ) {
        $output[] = '<span class="new product-label">' . esc_html__( 'New', 'woodmart' ) . '</span>';
    }

    if ( $product_attributes ) {
        foreach ( $product_attributes as $attribute ) {
            $output[] = $attribute;
        }
    }

    $output = apply_filters( 'woodmart_product_label_output', $output );

    if ( $output ) {
        woodmart_enqueue_inline_style( 'woo-mod-product-labels' );
        $shape = woodmart_get_opt( 'label_shape' );

        if ( 'rectangular' === $shape ) {
            woodmart_enqueue_inline_style( 'woo-mod-product-labels-rect' );
        }

        if ( 'rounded' === $shape ) {
            woodmart_enqueue_inline_style( 'woo-mod-product-labels-round' );
        }

        echo '<div class="product-labels labels-' . $shape . '">' . implode( '', $output ) . '</div>';
    }
}

add_filter( 'woocommerce_sale_flash', 'woodmart_product_label', 10 );

Попробуйте добавить в functions.php - правда это костыль
 

Romakod

Новичок
Код:
function woodmart_product_label() {
    global $product;

    $output = array();

    $product_attributes = woodmart_get_product_attributes_label();
    $percentage_label   = woodmart_get_opt( 'percentage_label' );

    if ( 'small' === woodmart_loop_prop( 'product_hover' ) ) {
        return;
    }

    if ( $product->is_on_sale() ) {

        $percentage = '';
        $not_percentage = '1';

        if ( $product->get_type() == 'variable' && $percentage_label ) {

            $available_variations = $product->get_variation_prices();
            $max_percentage       = 0;

            foreach ( $available_variations['regular_price'] as $key => $regular_price ) {
                $sale_price = $available_variations['sale_price'][ $key ];

                if ( $sale_price < $regular_price ) {
                    if ( $not_percentage == '1' ) {
                        $percentage = $regular_price - $sale_price;
                    } else {
                        $percentage = round( ( ( (float) $regular_price - (float) $sale_price ) / (float) $regular_price ) * 100 );
                    }
                   

                    if ( $percentage > $max_percentage ) {
                        $max_percentage = $percentage;
                    }
                }
            }

            $percentage = $max_percentage;
        } elseif ( ( $product->get_type() == 'simple' || $product->get_type() == 'external' || $product->get_type() == 'variation' ) && $percentage_label ) {
            if ( $not_percentage == '1' ) {
                $percentage = $product->get_regular_price() - $product->get_sale_price();
            } else {
                $percentage = round( ( ( (float) $product->get_regular_price() - (float) $product->get_sale_price() ) / (float) $product->get_regular_price() ) * 100 );
            }
           
        }

        if ( $percentage ) {
            if ( $not_percentage == '1' ) {
                $output[] = '<span class="onsale product-label">-' . $percentage . ' ₽</span>';
            } else {
                $output[] = '<span class="onsale product-label">' . sprintf( _x( '-%d%%', 'sale percentage', 'woodmart' ), $percentage ) . '</span>';
            }
           
        } else {
            $output[] = '<span class="onsale product-label">' . esc_html__( 'Sale', 'woodmart' ) . '</span>';
        }
       
    }

    if ( ! $product->is_in_stock() && 'thumbnail' === woodmart_get_opt( 'stock_status_position', 'thumbnail' ) ) {
        $output[] = '<span class="out-of-stock product-label">' . esc_html__( 'Sold out', 'woodmart' ) . '</span>';
    }

    if ( $product->is_featured() && woodmart_get_opt( 'hot_label' ) ) {
        $output[] = '<span class="featured product-label">' . esc_html__( 'Hot', 'woodmart' ) . '</span>';
    }

    if ( woodmart_get_opt( 'new_label' ) && woodmart_is_new_label_needed( get_the_ID() ) ) {
        $output[] = '<span class="new product-label">' . esc_html__( 'New', 'woodmart' ) . '</span>';
    }

    if ( $product_attributes ) {
        foreach ( $product_attributes as $attribute ) {
            $output[] = $attribute;
        }
    }

    $output = apply_filters( 'woodmart_product_label_output', $output );

    if ( $output ) {
        woodmart_enqueue_inline_style( 'woo-mod-product-labels' );
        $shape = woodmart_get_opt( 'label_shape' );

        if ( 'rectangular' === $shape ) {
            woodmart_enqueue_inline_style( 'woo-mod-product-labels-rect' );
        }

        if ( 'rounded' === $shape ) {
            woodmart_enqueue_inline_style( 'woo-mod-product-labels-round' );
        }

        echo '<div class="product-labels labels-' . $shape . '">' . implode( '', $output ) . '</div>';
    }
}

add_filter( 'woocommerce_sale_flash', 'woodmart_product_label', 10 );

Попробуйте добавить в functions.php - правда это костыль
Спасибо за помощь. Но выдает ошибку

error on line 2:

Невозможно повторно объявить функцию woodmart_product_label.
 

MacKor

Форумчанин
Странно ибо в теме вудмарт эта функция взята в условие эксист тем самым давая ее переопределить. Возможно у нас разные версии вудмарта.
 

Romakod

Новичок
А код добавляете в functions.php дочерней темы?
Здравствуйте, вставил в файл functions.php дочерней темы, до этого вставлял в плагин Code Snippets В результате появилась скидка но она неправильная и не изменяется в зависимости от вариации товара. Вот моя страница https://cv87810.tmweb.ru/katalog/pi...ity/dub/mebelnyj-shhit-rustikalnyj-s-suchkom/
 

MacKor

Форумчанин
Так и не должно меняться. В оригинальной версии тоже когда показывает проценты то показывает наибольшую скидку из все вариаций.
 

joy66

Опытный
Здравствуйте, вставил в файл functions.php дочерней темы, до этого вставлял в плагин Code Snippets В результате появилась скидка но она неправильная и не изменяется в зависимости от вариации товара. Вот моя страница https://cv87810.tmweb.ru/katalog/pi...ity/dub/mebelnyj-shhit-rustikalnyj-s-suchkom/
Для вариативных товаров так и есть. Вычисляется максимальная скидка из всех возможных и отображается типа "Скидки до 10000 руб"
Может , конечно есть где в сети решение. Как мне видится тут кроме кода (вроде того, что выше) надо еще jQuery код городить.
Не большой знаток JS/JQuery, но попробуйте в functions.php добавить.

Код:
add_action('wp_footer', 'din_sale_price',100);
function din_sale_price() {
       ?>
           <script type="text/javascript">
            (function($) {
             $(document).on('found_variation.first', function(event, variation){
                 thisvar=event.target;
                 $sale_price=variation.display_price;
                 $orig_price=variation.display_regular_price;
                 $discount=$orig_price-$sale_price;
                 if( thisvar && $discount > 0){
                  ptarget = thisvar.closest('li.product') ? thisvar.closest('li.product') : thisvar.closest('div.sale');
                  $splash= $(ptarget).find('span.onsale');
                   $splash.text("Скидка " + $discount +" руб.");

                }
            });
             })(jQuery, window, document)
           </script>
       <?php
}
 

Romakod

Новичок
Для вариативных товаров так и есть. Вычисляется максимальная скидка из всех возможных и отображается типа "Скидки до 10000 руб"
Может , конечно есть где в сети решение. Как мне видится тут кроме кода (вроде того, что выше) надо еще jQuery код городить.
Не большой знаток JS/JQuery, но попробуйте в functions.php добавить.

Код:
add_action('wp_footer', 'din_sale_price',100);
function din_sale_price() {
       ?>
           <script type="text/javascript">
            (function($) {
             $(document).on('found_variation.first', function(event, variation){
                 thisvar=event.target;
                 $sale_price=variation.display_price;
                 $orig_price=variation.display_regular_price;
                 $discount=$orig_price-$sale_price;
                 if( thisvar && $discount > 0){
                  ptarget = thisvar.closest('li.product') ? thisvar.closest('li.product') : thisvar.closest('div.sale');
                  $splash= $(ptarget).find('span.onsale');
                   $splash.text("Скидка " + $discount +" руб.");

                }
            });
             })(jQuery, window, document)
           </script>
       <?php
}
Получилось! Спасибо огромное вам!
 
Сверху Снизу