skip to Main Content

The default behavior of a Woocommerce AddToCart Button is to first show "Add to Cart". Once clicked, it will go to a Loading State and checks the AJAX request, then shows "in cart {number}".

I couldn’t find any action/filter to hook into. I can change the "Add to Cart" text in many different ways: hooks, translations, CSS, etc. But for the latter state, JavaScript is in charge, and, as a result even translation doesn’t work.

While I very much like this functionality, I have to find a way to replace "in cart" with an icon while keeping the {number} part.

Please let me know if you have robust and clean way of doing this.

Thank you in advance.

I tried reproducing the very structure of the HTML, even the wp-data attributes, but I couldn’t get far, since after replacing this with the default woocommerce html, the interactivity is gone.

I’m not that good at Javascript, but as ugly as it seems, I even tried to change it with a script that looks for the addedtocart event, and changes the text. In vain…

The obvious way is to create a customized button from scratch but I won’t be able to do it at this moment because I have other requirements to deliver.

I also tried whatever Chatgpt had to offer with its vast knowledge, to no success.

3

Answers


  1. Chosen as BEST ANSWER

    A rather clean solution I found:

    add_filter( 'gettext', function( $translated_text, $text, $domain ) {
        if ( 'woocommerce' === $domain && '%s in cart' === $text ) {
            $translated_text = ' %s';
        }
        return $translated_text;
    }, 10, 3 );
    

    I had tested translation, but I was expecting "%d in cart" which was wrong and I thought that's out of question. With "%s in cart" it works. I removed the "in cart" text and added the icon using a ::before psuedo-element.


  2. You can write custom javascript to do this
    When the button text changes to "in cart {number}", dynamically replace the text "in cart" with your desired icon (e.g., using HTML or a FontAwesome icon).

    you can write the javascript code in custom.js or function.php script file of your theme

    Here is the simple .js code which you can paste in custom.js in your theme

    document.addEventListener('DOMContentLoaded', function () {
        // Listen for changes in WooCommerce block buttons
        const observer = new MutationObserver(function (mutationsList) {
            for (let mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    const target = mutation.target;
                    // Check if the button text contains "in cart"
                    if (target.innerText.includes('in cart')) {
                        const match = target.innerText.match(/(d+)/); // Extract the number
                        if (match) {
                            const number = match[1];
                            // Replace button content with custom icon and number
                            target.innerHTML = `<span style="display: inline-flex; align-items: center;">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cart-check" viewBox="0 0 16 16">
                                  <path d="M10.97 4.97a.235.235 0 0 0-.304.304l1.28 3.211a.25.25 0 0 0 .233.176h2.54a.25.25 0 0 0 .234-.176l1.28-3.211a.235.235 0 0 0-.305-.304l-3.213 1.28a.235.235 0 0 0-.176.233v2.54a.235.235 0 0 0 .176.234l3.213 1.28a.235.235 0 0 0 .305-.305l-1.28-3.213a.25.25 0 0 0-.233-.176h-2.54a.25.25 0 0 0-.234.176l-1.28 3.213a.235.235 0 0 0 .305.305l3.213-1.28a.235.235 0 0 0 .176-.233v-2.54a.235.235 0 0 0-.176-.234l-3.213-1.28z"/>
                                  <path d="M5.5 1a1.5 1.5 0 0 1 1.415 1H13a.5.5 0 0 1 .485.621l-1 4a.5.5 0 0 1-.485.379H5.415a1.5 1.5 0 0 1-1.415 1A1.5 1.5 0 0 1 3 7.5V2.5A1.5 1.5 0 0 1 4.5 1zm0 1A.5.5 0 0 0 5 2.5v5a.5.5 0 0 0 0 1h7.565a.5.5 0 0 0 .485-.621l-1-4a.5.5 0 0 0-.485-.379H5z"/>
                                </svg>
                                &nbsp; ${number}
                            </span>`;
                        }
                    }
                }
            }
        });
    
        // Target WooCommerce Add to Cart Buttons
        const buttons = document.querySelectorAll('.wp-block-button__link'); // Adjust selector if needed
        buttons.forEach(button => {
            observer.observe(button, { childList: true, subtree: true });
        });
    });
    function custom_add_to_cart_button_script() {
        wp_enqueue_script('custom-add-to-cart', get_template_directory_uri() . '/js/custom.js', array('jquery'), false, true);
    }
    add_action('wp_enqueue_scripts', 'custom_add_to_cart_button_script');
    
    
    
    add_action('wp_footer', function () {
        ?>
        <script>
        /* Paste the JavaScript code here */
        </script>
        <?php
    });

    here how you add that .js function to your website

    Login or Signup to reply.
  3. Can you try this modified version? Its working here in my system.

    document.addEventListener("DOMContentLoaded", function () {
        // Function to replace "in cart {number}" with an icon + number
        function replaceInCartText(button) {
            const currentText = button.innerText;
            if (currentText.includes("in cart")) {
                const match = currentText.match(/(d+)/); // Extract the number
                if (match) {
                    const number = match[1];
                    // Replace button content with custom icon and number
                    button.innerHTML = `
                        <span style="display: inline-flex; align-items: center;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cart-check" viewBox="0 0 16 16">
                              <path d="M10.97 4.97a.235.235 0 0 0-.304.304l1.28 3.211a.25.25 0 0 0 .233.176h2.54a.25.25 0 0 0 .234-.176l1.28-3.211a.235.235 0 0 0-.305-.304l-3.213 1.28a.235.235 0 0 0-.176.233v2.54a.235.235 0 0 0 .176.234l3.213 1.28a.235.235 0 0 0 .305-.305l-1.28-3.213a.25.25 0 0 0-.233-.176h-2.54a.25.25 0 0 0-.234.176l-1.28 3.213a.235.235 0 0 0 .305.305l3.213-1.28a.235.235 0 0 0 .176-.233v-2.54a.235.235 0 0 0-.176-.234l-3.213-1.28z"/>
                              <path d="M5.5 1a1.5 1.5 0 0 1 1.415 1H13a.5.5 0 0 1 .485.621l-1 4a.5.5 0 0 1-.485.379H5.415a1.5 1.5 0 0 1-1.415 1A1.5 1.5 0 0 1 3 7.5V2.5A1.5 1.5 0 0 1 4.5 1zm0 1A.5.5 0 0 0 5 2.5v5a.5.5 0 0 0 0 1h7.565a.5.5 0 0 0 .485-.621l-1-4a.5.5 0 0 0-.485-.379H5z"/>
                            </svg>
                            &nbsp; ${number}
                        </span>`;
                }
            }
        }
    
        // Function to observe text changes in Add to Cart buttons
        function observeButtons() {
            const buttons = document.querySelectorAll(".wp-block-button__link, .add_to_cart_button");
    
            buttons.forEach((button) => {
                // Initial check for already "in cart" buttons
                replaceInCartText(button);
    
                // MutationObserver to watch for text changes
                const observer = new MutationObserver((mutationsList) => {
                    for (let mutation of mutationsList) {
                        if (mutation.type === "characterData" || mutation.type === "childList") {
                            setTimeout(() => replaceInCartText(button), 100); // Delay ensures WooCommerce's DOM changes complete
                        }
                    }
                });
    
                // Observe changes in the button
                observer.observe(button, {
                    childList: true,
                    subtree: true,
                    characterData: true,
                });
            });
        }
    
        // Observe WooCommerce buttons on page load
        observeButtons();
    
        // Re-check buttons after AJAX events (WooCommerce uses AJAX for cart updates)
        document.body.addEventListener("updated_wc_div", observeButtons); // For cart updates
        document.body.addEventListener("added_to_cart", observeButtons); // For successful adds
    });

    place the following code lines in custom-add-to-cart.js

    function enqueue_custom_cart_script() {
        wp_enqueue_script('custom-add-to-cart', get_template_directory_uri() . '/js/custom-add-to-cart.js', array('jquery'), false, true);
    }
    add_action('wp_enqueue_scripts', 'enqueue_custom_cart_script');
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search