0

I'm using code that displays a pop-up notification about adding a product to the cart.

    // Registration of styles and scripts
    add_action('wp_enqueue_scripts', 'enqueue_custom_woocommerce_popup_script');

    function enqueue_custom_woocommerce_popup_script() {
        // Registering Styles
        add_action('wp_head', 'custom_popup_css');

        // Enabling inline-JS in the footer
        add_action('wp_footer', 'custom_popup_js');
    }

    // CSS output function in head
    function custom_popup_css() {
    ?>
        <!-- Custom styles for the popup -->
        <style>
            .woo-add-to-cart-popup {
                position: fixed;
                top: 50px;
                right: 20px;
                background-color: #f8f8f8;
                color: black;
                padding: 10px 20px;
                border-radius: 5px;            
                font-size: 14px;
                z-index: 9999;
                transition: opacity 0.5s ease-in-out;
                animation: slideInRight 0.5s forwards;
            }

            @keyframes slideInRight {
                from {
                    transform: translateX(-10%);
                    opacity: 0;
                }
                to {
                    transform: translateX(0);
                    opacity: 1;
                }
            }
        </style>
    <?php
    }

    // The JavaScript output function immediately before the closing body tag
    function custom_popup_js() {
    ?>
    <script>
    jQuery(document).ready(function($) {
        function showPopup(message) {
            const popup = document.createElement("div");
            popup.className = "woo-add-to-cart-popup";
            popup.textContent = message;
            
            document.body.appendChild(popup);
            
            setTimeout(() => {
                popup.style.opacity = "0"; // Smooth fade
                setTimeout(() => {
                    document.body.removeChild(popup); // Removes the element completely after one second.
                }, 500); // Waiting time after the start of smooth fading
            }, 2000); // The message is displayed for 2 seconds.
        }

        $('body').on('added_to_cart', function(event, fragments, cart_hash, button) {
            let product_name = ''; // Variable for storing the product name

            // We check if we are on a single product page
            if($(button).closest('.single-product')) {
                // If yes, we extract the product name from the H1 heading
                product_name = $('.single-product .product_title').text(); 
            } else {
                // Otherwise, we consider this to be a shop page.
                product_name = $(button).closest('.product').find('.wd-entities-title').text();
            }

            // Additional check in case of missing text
            if(!product_name || product_name.trim().length === 0) {
                product_name = $(button).data('product_title') || '';
            }

            // Displaying a message about adding an item to the cart
            showPopup(`"${product_name}" added to cart`);
        });
    });
    </script>
    <?php
    }

My website uses the Woodmart theme, which uses different styles for the product title. On the single product page, the notification works correctly, but on the shop page, the product title doesn't appear in the notification.

Here is a screenshot of the HTML structure: screenshot

How can I correct my code so that the product title appears in the notification?

3
  • 1
    Any errors in the console? What happens if you log product_name to the console, right before invoking showPopup? If it's an empty string, then your button might be missing the data attribute you expect. EDIT One more thing to debug - add console.log("01/02/03") in your if/else checks to see where you're ending up. Commented Jan 24 at 14:29
  • There are no errors in the console. If I put console log after "IF" it shows the text "01/02/03." If I put console log after "ELSE" it shows nothing. Have you tried installing my code? Commented Jan 25 at 9:03
  • OK, since the first if check is where your code execution is going, can you verify that placing console.log(product_name) inside that if check shows what you expect? Regarding your question - no, unfortunately, I don't have the setup needed for this. But I'm assuming that this is a pure JS issue, and that we could easily get to the bottom of it. Commented Jan 25 at 13:53

1 Answer 1

1

I believe the issue with your code is that your shop page condition is never really being reached.

In your code you have:

// We check if we are on a single product page
if($(button).closest('.single-product')) {

But in JS/jQuery an object is always "truthy," even if it's empty. It returns an empty object, and an object is always true in a standard if statement. So your code always thinks it's on a single product page (true). It never reaches the shop page part of your code (false).

You can fix this by adding: .length to the code:

// We check if we are on a single product page
if($(button).closest('.single-product').length) {

This way you are checking for the number 0 (False) or 1 (True):

  • 0 = False (proceed to shop page logic)

  • 1 or more = True (proceed to single product logic)

It allows the code to jump to your next else statement where your shop page logic is.

I also added: popup.parentNode to your showPopup(message) function. It's a safety that checks if the popup still exists on the page before the code tries to remove it. It prevents errors if a user clicks the button multiple times quickly.

Full correct code:

// Registration of styles and scripts
add_action('wp_enqueue_scripts', 'enqueue_custom_woocommerce_popup_script');
function enqueue_custom_woocommerce_popup_script() {
    // Registering Styles
    add_action('wp_head', 'custom_popup_css');
    
    // Enabling inline-JS in the footer
    add_action('wp_footer', 'custom_popup_js');
}

// CSS output function in head
function custom_popup_css() {
    ?>
    <!-- Custom styles for the popup -->
    <style>
    .woo-add-to-cart-popup {
        position: fixed;
        top: 50px;
        right: 20px;
        background-color: #f8f8f8;
        color: black;
        padding: 10px 20px;
        border-radius: 5px;            
        font-size: 14px;
        z-index: 9999;
        transition: opacity 0.5s ease-in-out;
        animation: slideInRight 0.5s forwards;
        }
        @keyframes slideInRight {
            from {
                transform: translateX(-10%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>
    <?php
}

// The JavaScript output function immediately before the closing body tag
function custom_popup_js() {
    ?>
    <script>
    jQuery(document).ready(function($) {
        function showPopup(message) {
            const popup = document.createElement("div");
            popup.className = "woo-add-to-cart-popup";
            popup.textContent = message;
            
            document.body.appendChild(popup);
            
            setTimeout(() => {
                popup.style.opacity = "0"; // Smooth fade
                setTimeout(() => {
                
                    // Added safety check (popup.parentNode)
                    if(popup.parentNode) document.body.removeChild(popup); // Removes the element completely after one second.
                }, 500); // Waiting time after the start of smooth fading
            }, 2000); // The message is displayed for 2 seconds.
        }

        $('body').on('added_to_cart', function(event, fragments, cart_hash, button) {
            let product_name = ''; // Variable for storing the product name

            // We check if we are on a single product page
            // Added .length so the "else" block can actually be reached
            if($(button).closest('.single-product').length) {
                // If yes, we extract the product name from the H1 heading
                product_name = $('.single-product .product_title').text(); 
            } else {
                // Otherwise, we consider this to be a shop page.
                product_name = $(button).closest('.product').find('.wd-entities-title').text();
            }

            // Additional check in case of missing text (Your original trim is here)
            if(!product_name || product_name.trim().length === 0) {
                product_name = $(button).data('product_title') || '';
            }

            // Displaying a message about adding an item to the cart
            showPopup(`"${product_name}" added to cart`);
        });
    });
    </script>
    <?php
}

I have tested this code specifically in the WoodMart theme, and it works. Just remember that this requires "AJAX add to cart" enabled.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.