Lightbox popup on WooCommerce add_to_cart action

The following works for me for product archive pages (these include both the main shop page as well as archive pages for product categories, for example).

It will show the current cart contents in a thickbox. I chose to show this for this example just because that’s the data that one gets back through Ajax after clicking the add-to-cart button, but you may want a different kind of info in your box. You can get the product_id of the product just added, for example, by looking at surrounding html elements.

In your theme’s functions.php (or in the class definition for the theme, if you have one) there’s probably some ‘enqueue_scripts’ function. You should add this to this function to ensure the thickbox script is loaded.

if (is_woocommerce() && is_archive()) {
    wp_enqueue_script( 'frontend-custom', get_template_directory_uri() . '/js/frontend-custom.js', array("jquery"));
    add_thickbox();
}

In a file (in your theme directory) js/frontend-custom.js (or wherever you have your theme’s js):

jQuery(document).ready(function($) {
    $('body').on('added_to_cart',function(e,data) {
        //alert('Added ' + data['div.widget_shopping_cart_content']);
        if ($('#hidden_cart').length == 0) { //add cart contents only once
            //$('.added_to_cart').after('<a href="#TB_inline?width=600&height=550&inlineId=hidden_cart" class="thickbox">View my inline content!</a>');
            $(this).append('<a href="#TB_inline?width=300&height=550&inlineId=hidden_cart" id="show_hidden_cart" title="<h2>Cart</h2>" class="thickbox" style="display:none"></a>');
            $(this).append('<div id="hidden_cart" style="display:none">'+data['div.widget_shopping_cart_content']+'</div>');
        }
        $('#show_hidden_cart').click();
    });
});

Some additional notes:

  • I suppose you can also output javascript directly into the page from php. In this case, I think you probably want to hook with add_action('woocommerce_ajax_added_to_cart', 'myfunction');
    This action is run inside woocommerce_ajax_add_to_cart() right after adding an item to the cart (passing validation, etc), but before redirecting.

  • The single product pages do not work in the same way (‘add to cart’ is there a normal php form, no ajax is involved).

  • I haven’t tested this, but WooCommerce comes with its own ‘prettyphoto.js’, which works by adding ‘rel=”prettyPhoto”‘ to an href link, pretty much as the thickbox class works in the above example. You might want to give it a try to keep design consistency with WooCommerce.

Leave a Comment