0

Я использую код, который изменяет текст и стиль кнопки «Добавить в корзину» для товара, добавленного в корзину.

/* for single product */
add_filter( 'woocommerce_product_single_add_to_cart_text', 'single_product_button_text' );
 
function single_product_button_text( $text ) {
 
    if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( get_the_ID() ) ) ) {
        $text = 'Product in Сart';
    }
 
    return $text;
 
}
 
/* for archive/category pages */
add_filter( 'woocommerce_product_add_to_cart_text', 'products_button_text', 20, 2 );
 
function products_button_text( $text, $product ) {
 
    if( 
       $product->is_type( 'simple' )
       && $product->is_purchasable()
       && $product->is_in_stock()
       && WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) )
    ) {
 
        $text = 'Product in Сart';
 
    }
 
    return $text;
 
}

add_action( 'wp_footer', 'action_wp_footer' );
function action_wp_footer() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            var selector = '.add_to_cart_text:contains("Product in Сart")';
            
            // Selector contains specific text
            if ( $( selector ).length > 0 ) {
                $( selector ).addClass( 'product-is-added' );
            } else {
                $( selector ).removeClass( 'product-is-added' );            
            }
            
        });
    </script>
    <?php
}

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

Далее я использовал код для изменения текста и стиля кнопки с помощью AJAX. Текст меняется, но все стили ломаются.

add_action('wp_footer','custom_jquery_add_to_cart_script');
function custom_jquery_add_to_cart_script(){
    if ( is_shop() || is_product_category() || is_product_tag() ): // Only for archives pages
        $new_text = __( 'Product in Сart', 'woocommerce' );
        ?>
            <script type="text/javascript">
                // Ready state
                (function($){
                    $('a.add_to_cart_button').click( function(){
                        $this = $(this);
                        $( document.body ).on( 'added_to_cart', function(){
                            $($this).text('<?php echo $new_text; ?>');
                            console.log('EVENT: added_to_cart');
                        });
                    });

                })(jQuery); 
            </script>
        <?php
    endif;
}

Как я могу исправить этот код в своем вопросе? Может есть более корректный вариант кода?

Буду рад вашей помощи!

1 ответ 1

0

Возможно кому-нибудь пригодится данный ответ. Моя тема имеет много кастомного кода, включая шаблоны списка товаров, поэтому вам нужно поменять стили под свои нужды. Либо можете этот код усовершенствовать.

add_action( 'wp_footer', 'ajax_button_text_js_script' );
function ajax_button_text_js_script() {
    $text = __('Product in Cart', 'woocommerce');
    ?>
    <script>
        jQuery(function($) {
            var text = '<?php echo $text; ?>',      $this;

            $(document.body).on('click', '.ajax_add_to_cart', function(event){
                $this = $(this); 
            });

            $(document.body).on('added_to_cart', function(event,b,data){
                var buttonText = '<span class="add_to_cart_text product-is-added">'+text+'</span><i class="cart-icon"></i>';

                $this.html(buttonText).attr('data-tip',text);
            });
        });
    </script>
    <?php
}

Код нужно добавить в файл functions.php вашей дочерней темы. Код протестирован и работает.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.