G
G
graf452312019-09-15 17:40:11
WordPress
graf45231, 2019-09-15 17:40:11

How to change the price of an item when adding to cart?

Made a plugin for adding monograms to WooCommerce products. I use hooks to add monogram data to product meta data, products are variable. Here is the code in functions.php

//Monogramma
add_filter('woocommerce_add_cart_item_data', 'MTWC_add_item_data', 10, 3);

function MTWC_add_item_data($cart_item_data, $product_id, $variation_id)
{
    if( isset($_REQUEST['mono_check']))
    {
        $cart_item_data['mono_check'] =  $_REQUEST['mono_check'];
        if( isset($_REQUEST['mono_symbols']))
        {
            $cart_item_data['mono_symbols'] =  $_REQUEST['mono_symbols'];
        }
        if( isset($_REQUEST['mono_type']))
        {
            $cart_item_data['mono_type'] =  $_REQUEST['mono_type'];
        }
    }

    return $cart_item_data;
}
add_filter('woocommerce_get_item_data', 'MTWC_add_item_meta', 10, 2);

function MTWC_add_item_meta($item_data, $cart_item)
{
    if(array_key_exists('mono_check', $cart_item))
    {
        if($cart_item['mono_check'] == "on")
            $custom_details = "Есть";
        else
            $custom_details = "Нет";

        $item_data[] =  array(
            'key'   =>  'Монограмма',
            'value' => $custom_details.", Тип монограммы: ".$cart_item['mono_type'].", Символы: ".$cart_item['mono_symbols'],
        );
    }

    return $item_data;
}
add_action( 'woocommerce_checkout_create_order_line_item', 'MTWC_add_custom_order_line_item_meta', 10, 4 );

function MTWC_add_custom_order_line_item_meta($item, $cart_item_key, $values, $order)
{
    if(array_key_exists('mono_check', $values))
    {
        if($values['mono_check'] == "on")
            $custom_details = "Есть";
        else
            $custom_details= "Нет";

        $item->add_meta_data('Монограмма', $custom_details.", Тип монограммы: ".$values['mono_type'].", Символы: ".$values['mono_symbols']);
    }
}

How do I change the code to change the price of an item?
And not yet related to this question, but still would like some hints on this...
Monogram data is sometimes not transmitted. That is, the hook does not catch the transmitted data regarding my plugin.
Here is the code for the plugin area itself, it is added as a shortcode right before the add to cart button, that is, it is located inside the send to cart form.
<?php if (count($this->data['preview']) != 0): ?>
    <div class="adv preview">
        <input type="checkbox" name="mono_check" onclick="isChecked(this)"/>
        <label for="mono_check">Добавить монограмму</label>
        <div class="hidden overlay" onclick="overlayShowHide()"
             style="position: fixed;                   background: rgba(0, 0, 0, 0.5);                   top: 0;                   bottom: 0;                   left: 0;                   right: 0;                   z-index: 9999;            ">
            <div class="prev-panel" onclick="event.stopPropagation()">
                <div class="close_btn" onclick="overlayShowHide()">X</div>
                <h2>Предпросмотр</h2>
                <div class="monos">
                    <div class="mono_btn mono_btn_1"
                         style="background-image: url('<? echo $this->plugin_url ?>/monos/1.png')"
                         onclick="selectMono(this)" data-count="2" data-type="1"><p>R</p>
                        <p>A</p></div>
                    <div class="mono_btn mono_btn_2"
                         style="background-image: url('<? echo $this->plugin_url ?>/monos/2.png')"
                         onclick="selectMono(this)" data-count="2" data-type="2"><p>A</p>
                        <p>B</p></div>
                    <div class="mono_btn mono_btn_3"
                         style="background-image: url('<? echo $this->plugin_url ?>/monos/3.png')"
                         onclick="selectMono(this)" data-count="1" data-type="3"><p>M</p></div>
                    <div class="mono_btn mono_btn_4"
                         style="background-image: url('<? echo $this->plugin_url ?>/monos/4.png')"
                         onclick="selectMono(this)" data-count="1" data-type="4"><p>M</p></div>
                    <div class="mono_btn mono_btn_5"
                         style="background-image: url('<? echo $this->plugin_url ?>/monos/5.png')"
                         onclick="selectMono(this)" data-count="3" data-type="5"><p>M</p>
                        <p>A</p>
                        <p>G</p></div>
                    <div class="mono_btn mono_btn_6" onclick="selectMono(this)" data-count="2" data-type="6"><p>S&P</p>
                    </div>
                    <div class="mono_btn mono_btn_7" onclick="selectMono(this)" data-count="1" data-type="7"><p>A</p>
                    </div>
                </div>
                <p class="input_text">Введите 1 символ</p> 
                <input name="mono_symbols" class="symbols"
                                                                                type="text" onchange="symbol(this)"
                                                                                onkeyup="this.value = this.value.toUpperCase();"
                                                                                maxlength="3"/> <input name="mono_type"
                                                                                                       class="mono_type hidden"
                                                                                                       type="text"/>
                <div class="prev_image" style="background-image: url(<? echo $this->data['preview']['prev_src'] ?> )"
                     onclick="look(this)">
                    <div style="background-image: url('<? echo $this->plugin_url ?>monos/2.png'); left: <?php echo $this->data['preview']['prev_X'] ?>; top: <?php echo $this->data['preview']['prev_Y'] ?>;  width: <?php echo $this->data['preview']['preview_size'] ?>px" class="draggable"/>
                </div>
            </div>
        </div>
    </div>
</div>

But below is the code inside the "variation-add-to-cart-button.php" template.
Everything works fine on my site, but on the site where I put the plugin, it refuses to work normally. My site is at least loaded with plugins, it costs only woocommerce and a couple of auxiliary plugins that are not related to woocommerce, but my friend’s site uses a bunch of plugins that are directly related to woocommerce. How to understand what is the problem? It does not send the monogram meta data when the item is shipped.
When changing the onclick of the button for sending goods to the basket, it began to send data, but not always, sometimes it does not send. understand why this is not happening. I'm just learning to write plugins, don't judge strictly.
<?
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
    if(is_plugin_active( 'monogramm-to-woocommerce/monogramm-to-woocommerce.php' )) {
        echo do_shortcode('[show_preview]');
    }
    ?>
    <script>
        document.querySelector('form.variations_form.cart [type="submit"]').onclick = function (e) {
                e.preventDefault();
                document.querySelector('form.variations_form.cart').submit();
            }
    </script>

I've been struggling with this for the third day now, I can't figure it out. If any data is missing, then write, I will throw everything off.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
graf45231, 2019-09-15
@graf45231

I solved the first problem by adding one function and editing the written one. Here is the code, maybe someone will need it.

function MTWC_add_item_data($cart_item_data, $product_id, $variation_id)
{
    if( isset($_REQUEST['mono_check'])) {
        $cart_item_data['mono_check'] = $_REQUEST['mono_check'];
        if (isset($_REQUEST['mono_symbols'])) {
            $cart_item_data['mono_symbols'] = $_REQUEST['mono_symbols'];
        }
        if (isset($_REQUEST['mono_type'])) {
            $cart_item_data['mono_type'] = $_REQUEST['mono_type'];
        }
        //Запоминаем новую цену товара при отправке в корзину
        $product = wc_get_product($product_id); 
        $price = $product->get_price();
        $cart_item_data['warranty_price'] = $price + 700;
    }
    return $cart_item_data;
}
add_filter('woocommerce_get_item_data', 'MTWC_add_item_meta', 10, 2);

//Меняем цену товара перед расчетом цены
function before_calculate_totals( $cart_obj ) {
    foreach( $cart_obj->get_cart() as $key=>$value ) {
        if( isset( $value['warranty_price'] ) ) {
            $price = $value['warranty_price'];
            $value['data']->set_price( ( $price ) );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals', 10, 1 );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question