Is there a way to hook into WooCommerce BEFORE item is added to cart

Does anyone know of a filter or hook that can be applied to insert a function before an item is inserted into a cart using WooCommerce? I have a similar issue as this post:

WordPress. Woocommerce. Action hook BEFORE adding to cart

Read More

But that OP’s comments don’t seem to work or are so vague I can’t get them to work and I can find no documentation regarding woocommerce_before_add_to_cart.

What I’m trying to do is just display an error, I’ll add logic once I can hook into the right action:

function checkProd(){
global $woocommerce;
$woocommerce->add_error( __('ERROR', 'woocommerce') );
return;
}
add_action( 'woocommerce_variable_add_to_cart', 'checkProd');

Related posts

Leave a Reply

2 comments

  1. The best resource that I’ve found for woocommerce hooks is actually the repository itself, they have incredibly well commented code that is very readable.

    https://github.com/woocommerce/woocommerce/blob/master/includes/wc-template-hooks.php

    I’m sure a solution exists for the problem you’re trying to solve in one of these sections:

    /**
     * Product Add to cart
     *
     * @see woocommerce_template_single_add_to_cart()
     * @see woocommerce_simple_add_to_cart()
     * @see woocommerce_grouped_add_to_cart()
     * @see woocommerce_variable_add_to_cart()
     * @see woocommerce_external_add_to_cart()
     */
    add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    add_action( 'woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30 );
    add_action( 'woocommerce_grouped_add_to_cart', 'woocommerce_grouped_add_to_cart', 30 );
    add_action( 'woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30 );
    add_action( 'woocommerce_external_add_to_cart', 'woocommerce_external_add_to_cart', 30 );
    
    
    /**
    * Cart Actions
    *
    * @see woocommerce_update_cart_action()
    * @see woocommerce_add_to_cart_action()
    * @see woocommerce_load_persistent_cart()
    */
    add_action( 'init', 'woocommerce_update_cart_action' );
    add_action( 'init', 'woocommerce_add_to_cart_action' );
    add_action( 'wp_login', 'woocommerce_load_persistent_cart', 1, 2 );
    

    If you continue to have issues leveraging the above action hooks feel free to throw me a few more details and I can try to walk you through. Good luck!

  2. I needed to do some actions before add to cart, so I did it this way

    add_action('init', function(){
        //if user clicked http://example.com/shop/?add-to-cart=42
        if(!is_admin() && isset($_REQUEST['add-to-cart'])){
            //do something
        }
    });
    

    $_REQUEST used to process both GET and POST requests.