skip to Main Content

pic

I want the ‘voir le panier’ button to remain visible for products I’ve added to my cart in WooCommerce, even after refreshing the page. Right now, the buttons disappear when I refresh. I need help with this feature to ensure that the product remains displayed, similar to the example in the attached image.

i have added this ti add-to-cart.php

<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

global $product;
$product_id = $product->get_id();
$cart = WC()->cart->get_cart();
$is_in_cart = false;

// Check if the product is already in the cart
foreach ( $cart as $cart_item ) {
    if ( $cart_item['product_id'] == $product_id ) {
        $is_in_cart = true;
        break;
    }
}

// Output the "Ajouter au Panier" button
$add_to_cart_button = sprintf(
    '<a href="%s" data-quantity="%s" class="button-primary xsmall rounded wide %s add-to-cart-button" data-product_id="%d" %s>%s</a>',
    esc_url( $product->add_to_cart_url() ),
    esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ),
    esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ),
    esc_attr( $product_id ),
    isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '',
    esc_html( $product->add_to_cart_text() )
);

// Show the "Ajouter au Panier" button
echo $add_to_cart_button;

// Show "Voir le Panier" button if the product is in the cart
if ( $is_in_cart ) {
    echo sprintf(
        '<a href="%s" class="button voir_panier_button" style="display:block;">%s</a>',
        esc_url( wc_get_cart_url() ),
        esc_html__( 'Voir le Panier', 'woocommerce' )
    );
}
?>

<script type="text/javascript">
    jQuery(document).ready(function($) {
        let viewCartButtonShown = false;

        $('.add-to-cart-button').on('click', function(e) {
            e.preventDefault();
            var button = $(this);
            var productId = button.data('product_id');
            var viewCartButton = $('.voir_panier_button');

            // Check if the product is already in the cart
            if (viewCartButton.length === 0) {
                // If the "Voir le Panier" button is not already shown
                button.parent().append(viewCartButton);
                viewCartButton.show();
                viewCartButtonShown = true; // Mark the button as shown
            } else {
                // If the product is already in the cart, hide the "Voir le Panier" button
                viewCartButton.hide();
            }

            // Optional: Hide the "added_to_cart wc-forward" button
            $('.added_to_cart.wc-forward').hide();
        });
    });
</script>

2

Answers


  1. Chosen as BEST ANSWER

    thanks brother for the help iv try it before and still same problem but i did and alternative solution based on java that it change the text and the color of the button but the only thing im have issue with now is when i remove somthiing from the cart the button dosent back to intial state this is the code i used :

    // Wait for the DOM to be fully loaded
    document.addEventListener('DOMContentLoaded', function() {
        // Function to update button state based on localStorage
        function updateButtonState(button, productId) {
            if (localStorage.getItem(`product_${productId}_added`) === 'true') {
                button.classList.add('added');
                button.style.backgroundColor = 'grey'; // Change to grey
                button.textContent = 'ajoutez-en un autre'; // Updated text
            } else {
                button.classList.remove('added');
                button.style.backgroundColor = 'green'; // Change to green
                button.textContent = 'Ajouter au panier'; // Reset text to initial
            }
        }
    
        // Get all "Add to Cart" buttons
        const buttons = document.querySelectorAll('.button-primary.xsmall.rounded.wide.button.product_type_simple.add_to_cart_button.ajax_add_to_cart');
    
        buttons.forEach(button => {
            const productId = button.getAttribute('data-product_id');
    
            // Initial check for button state
            updateButtonState(button, productId);
    
            // Add click event listener
            button.addEventListener('click', function() {
                // Change button style and text when clicked
                button.classList.add('added');
                button.style.backgroundColor = 'grey'; // Change to grey
                button.textContent = 'ajoutez-en un autre'; // Updated text
    
                // Store the state in localStorage
                localStorage.setItem(`product_${productId}_added`, 'true');
            });
        });
    
        // Function to check cart updates (This may vary depending on your setup)
        function checkCartUpdates() {
            buttons.forEach(button => {
                const productId = button.getAttribute('data-product_id');
                const isAdded = localStorage.getItem(`product_${productId}_added`) === 'true';
    
                if (!isAdded) {
                    // Update button state based on cart contents
                    updateButtonState(button, productId);
                }
            });
        }
    
        // Function to handle item removal from cart
        function handleItemRemoval(productId) {
            localStorage.removeItem(`product_${productId}_added`);
            buttons.forEach(button => {
                if (button.getAttribute('data-product_id') === productId) {
                    updateButtonState(button, productId);
                }
            });
        }
    
        // Use MutationObserver to monitor changes to the cart
        const cartObserver = new MutationObserver(checkCartUpdates);
        const cartElement = document.querySelector('.woocommerce-cart'); // Adjust selector based on your cart element
        if (cartElement) {
            cartObserver.observe(cartElement, { childList: true, subtree: true });
        }
    
        // Example of how to call handleItemRemoval when an item is removed from the cart
        // This part depends on how your cart removal is implemented
        document.addEventListener('click', function(event) {
            if (event.target.matches('.remove_from_cart_button')) {
                const productId = event.target.getAttribute('data-product_id');
                handleItemRemoval(productId);
            }
        });
    });


  2. To ensure that the Voir le Panier button remains visible for products that are already in the cart even after a page refresh in WooCommerce, you’ll need to ensure that your PHP and Javascript logic are correctly handling the state persistence. From what you’ve provided the PHP part of your logic seems mostly set up to check if the product is in the cart and then show the button. However, there might be some tweaks necessary to ensure everything works seamlessly across page reloads.

    First, the following refined code is for PHP part to check the cart status.

    // remaining part of code 
    echo sprintf(
        '<a href="%s" data-quantity="%s" class="button add-to-cart-button %s" data-product_id="%d" %s>%s</a>',
        esc_url($product->add_to_cart_url()),
        esc_attr(isset($args['quantity']) ? $args['quantity'] : 1),
        esc_attr(isset($args['class']) ? $args['class'] : 'button'),
        esc_attr($product_id),
        isset($args['attributes']) ? wc_implode_html_attributes($args['attributes']) : '',
        esc_html($product->add_to_cart_text())
    );
    // remaining part of code. 
    

    For Javascript refinement you can do something like this:

    <script type="text/javascript">
    jQuery(document).ready(function($) {
        // This could be simplified or even unnecessary if PHP is doing its job correctly
        var productId = '<?php echo $product_id; ?>';  // Make sure product ID is echoed correctly in JS
        var isInCart = <?php echo $is_in_cart ? 'true' : 'false'; ?>;
    
        if (isInCart) {
            $('.voir_panier_button').show();  // Make sure this class matches the button you want to show
        } else {
            $('.voir_panier_button').hide();
        }
    });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search