Woocommerce add_to_cart hook empties cart

I’m using the woocommerce_add_to_cart action hook like so:

add_action('woocommerce_add_to_cart', 'display_more_modal', 10, 6);

function display_more_modal( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {

    echo "<h1>Test Title here...</h1>";

    //or

   ?>
   <h1>More text here</h1>
   <?php

}

I have found that if I echo out HTML or output HTML, as illustrated above, it removes all items from the cart, once I go the cart to view what I have added.

Read More

Could you some illustrate what I am possibly doing wrong? I have a suspicion that I have to return a value instead of echoing it.

If this is the case, please help as to how I can echo out HTML when a user adds a product to the cart. This HTML will be a popup with related products. Thank you.

Related posts

1 comment

  1. I figured that some hooks within WordPress don’t like echoing anything out. I’m not sure how hard & fast this rule is but I remember it generally tends to be bad practice to echo anything out within functions. Instead they should return something. I simply created the product which was created and returned that. In the view file I created an if statement which outputs the html for the modal if a product exists. That seems to have fixed it.

Comments are closed.