Странное поведение woocommerce - изменение данных о ценах вариаций (казалось бы, случайных значений) до выбора пользователем вариаций - PullRequest
0 голосов
/ 27 февраля 2020

У меня странная проблема, с которой я никогда не сталкивался, и я не совсем уверен, где искать решение.


РЕДАКТИРОВАТЬ -

Проблема Я имею в виду, что цена, отображаемая до того, как пользователь выберет вариант, создается случайным образом. Например, «Переменный продукт A» имеет «красный» вариант за 100,00 долларов США. Перед тем, как пользователь выберет «красный» вариант, цена должна отображаться как 0,00 долл., Но вместо этого иногда он показывает 0,00 долл., А иногда - 54,99, 119,99 долл., 64,99 долл. И т. Д. c ... После того, как пользователь выбрал вариант, все работает отлично. Непосредственно перед тем, как они сделают выбор.


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

add_filter( 'woocommerce_get_price_html', 'change_price_html', 100, 2 );

function change_price_html( $price, $product ){

    global $post, $product;

    $classes = get_body_class();
    $products_id = $product->get_id();

    $pb_1_qty = 10;
    $pb_2_qty = 20;
    $break_1_discount_multiplier = 0.91;
    $break_2_discount_multiplier = 0.82;

    if($product->is_type('simple')){ (/*removed code for question*/}
    elseif($product->is_type('variable')){
        echo '
            <script type="text/template" id="tmpl-variation-template">
                <div class="woocommerce-variation-description">
                    {{{ data.variation.variation_description }}}
                </div>
                <div class="woocommerce-variation-price">
                    <table class="pricing-table">
                        <tbody>
                            <tr>
                                <th>1 - '.($pb_1_qty-1).'</th>
                                <th>'.$pb_1_qty.' - '.($pb_2_qty-1).'</th>
                                <th>'.$pb_2_qty.'+</th>
                            </tr>
                            <tr>
                                <td id="pricing-table-full-price">${{{ ( data.variation.display_price.toFixed(2)) }}}</td>
                                <td id="pricing-table-35">${{{ (( data.variation.display_price.toFixed(2))*.91).toFixed(2) }}}</td>
                                <td id="pricing-table-45">${{{ (( data.variation.display_price.toFixed(2))*.82).toFixed(2) }}}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="woocommerce-variation-availability">
                    {{{ data.variation.availability_html }}}
                </div>
            </script>
            <script type="text/template" id="tmpl-unavailable-variation-template">
                <p>Sorry, this product is unavailable. Please choose a different combination</p>
            </script>
            ';
        } else {
            return $price;
        }
    }

Приведенный выше код был создан с помощью ссылки на шаблон отображения одного варианта по умолчанию в woocommerce-> templates-> single-product-> add-to-cart-> extension. php, который использует javascript шаблоны для получения цены вариации.

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


// PRICE DISPLAY FUNCTION ON SINGLE PRODUCT PAGES

//Adds a new subtotal line and hides PAO default subtotal line. I was getting errors trying to use the subtotal area from the woocommerce product addons plugin, so I used my own area.

add_action('woocommerce_before_add_to_cart_button', 'pao_live_subtotal');
function pao_live_subtotal(){
    echo '<span id="liveSubtotalContainer">Subtotal: <span id="liveSubtotal">$0.00 </span></span>';
    echo '<style>.product-addon-totals{display:none;}</style>';
}

//Live updates of prices
//Found that below script will not load if not called after footer
add_action('storefront_after_footer', 'pao_live_price_update',0,0);

function pao_live_price_update(){
    ?>

        <script>
            document.body.onload = addElement;

            function addElement () {
                var newTable = document.createElement("table");
                newTable.id = "pricing-table-full-price";
                var currentDiv = document.querySelector(".woocommerce-variation.single_variation");
                currentDiv.appendChild(newTable);
    //because the table is pushed through the get_price_html, I was getting errors using javascript to select the table, so I created this table with ID to avoid errors later when using js to call elements that are dynamically created.
            }

            var y = document.querySelector('form.cart');
            var z = y.querySelector('input.qty');

            y.onchange = function() {
                if(z.value < 10 && z.value >= 1) {
                    var multiplier = 1;
                    var subtotal = document.getElementById('liveSubtotal');
                    if(document.getElementById('pricing-table-full-price') != null) {
                        var ogp = document.getElementById('pricing-table-full-price').innerText.replace('$','');
                        var fixedp = parseFloat(ogp).toFixed(2);
                        var newp = (fixedp*multiplier).toFixed(2);
                        //console.log(newp);
                        subtotal.innerText = '$' + (newp*z.value).toFixed(2);
                    }
                    else {
                        console.log('null');
                    }
                }
                else if(z.value >= 10 && z.value < 20) {
                    var multiplier = .91;
                    var subtotal = document.getElementById('liveSubtotal');
                    if(document.getElementById('pricing-table-full-price') != null) {
                        var ogp = document.getElementById('pricing-table-full-price').innerText.replace('$','');
                        var fixedp = parseFloat(ogp).toFixed(2);
                        var newp = (fixedp*multiplier).toFixed(2);
                        //console.log(newp);
                        subtotal.innerText = '$' + (newp*z.value).toFixed(2);
                    }
                    else {
                        console.log('null');
                    }
                }
                else if(z.value >= 20) {
                    var multiplier = .82;
                    var subtotal = document.getElementById('liveSubtotal');
                    if(document.getElementById('pricing-table-full-price') != null) {
                        var ogp = document.getElementById('pricing-table-full-price').innerText.replace('$','');
                        var fixedp = parseFloat(ogp).toFixed(2);
                        var newp = (fixedp*multiplier).toFixed(2);
                        //console.log(newp);
                        subtotal.innerText = '$' + (newp*z.value).toFixed(2);
                    }
                    else {
                        console.log('null');
                    }
                }
                else { /*do nothing */ }
            }
        </script>
    <?php


}

...