add modal to woocommerce add to cart button

I am building a wordpress site with woocommerce.

I want to add an optional insurance product that pops up when a customer clicks on ‘add to cart’ for a particular product. The idea is that they have to accept or decline this product before they continue to the checkout.

Read More

I have tried using bootstrap modal but I can’t get it to trigger using the add to cart button.
Modal is working fine as a specific modal button built into the page, so I know it’s not a problem with jquery or bootstrap, but I can’t figure out how link it to the add to cart button.

Seems like something that should be built-in to woocommerce already but if it is I’ve missed it.

Any help much appreciated…

Related posts

Leave a Reply

3 comments

  1. I ended up setting the modal to trigger when the cart page opened, as the cart page is WordPress it was straight-forward. Not the perfect solution as the modal now opens when a customer goes to buy any product, but it’s better than nothing.
    here’s the code with the default content

    <div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
             <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
               <h4 class="modal-title" id="myModalLabel">Modal title</h4>
           </div>
        <div class="modal-body">
        ...
        </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
      </div><!-- /.modal -->
    
    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
      Launch demo modal
    </button>     
    

    and the js

    <script>
     jQuery(document).ready(function($) {
     $(document).ready(function(){
     $('#myModal').modal('show')
     });
      });
     </script>
    

    I inserted all this directly in the ‘your cart’ wordpress page.

    Works fine, but I’d love to hear a better solution

  2. by adding a query to checks if current url contains the string ‘add-to-cart’, you can show the modal in your shop page. You should also uncheck ‘Redirect to the cart page after successful addition’ under: WooCommerce > Settings > Products > Display.

    <script>
    jQuery(document).ready(function () {
        if (window.location.href.indexOf("add-to-cart") != -1){
            $('#cartModal').modal('show');
        }
    });
    </script>