skip to Main Content

On the WordPress homepage, there is a section called Best Sellers that showcases best sellers in the website. In summary, these are nothing but various products with Add to Cart link, in Woocommerce loop. When this Add to Cart link is clicked, I need to be able to read all information regarding the product that was just now added to cart, such as its ID, Quantity, Variant ID, etc. via AJAX or however WordPress/Woocommerce does it WITHOUT reloading the page.

NOTE:

Please note whatever function is used to accomplish this task, should not interfere with the functionality of Single Product page when the Add to Cart button in Single Product page is clicked. It is completely fine if the desired functionality cascades to other parts of the website such as Shop, Archive, etc. but NOT the Single Product page.

WHAT I TRIED:

add_action('wp_footer', 'my_loop_add_to_cart', 21);
function my_loop_add_to_cart() {
    //What code should I write here to access the recently added to cart item? 
}

I am ok with changing the hook if the need be, just want to make sure that it does not interfere with the functionality of the Add to Cart link/button in the Single Product page.

2

Answers


  1. There are a couple of options to do this.
    One I can think of is using woocommerce_add_to_cart action hook.

    add_action( 'woocommerce_add_to_cart', 'rmg_woocommerce_add_to_cart', 10, 6 );
    function rmg_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
        // do something with $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data
    }
    
    Login or Signup to reply.
  2. There is one hook named woocommerce_after_shop_loop_item which will work for related products and shop page products listing only.

    add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 9 );
    
    
    function woocommerce_template_loop_add_to_cart()
    {
       global $woocommerce;
       $items = $woocommerce->cart->get_cart();
       $last_added_item_details = end($items)['data'];
    }
    

    Tested and works well

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search