I am working on a plugin and I am stuck on something.
I want to add a product to cart on submit.
At first I got an error that WP Wasn’t loaded. So I fixed this by using
add_action('wp_loaded', 'wp_after_load');
So here is my code:
HTML
<form method="POST" enctype="multipart/form-data">
<button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button>
</form>
PHP
if (isset($_REQUEST['ws-add-to-cart'])) {
add_action('wp_loaded', 'wp_after_load');
}
function wp_after_load() {
add_action( 'init', 'add_product_to_cart' );
}
function add_product_to_cart() {
echo '<script>alert("dsa");</script>';
global $woocommerce;
global $product;
$product_ident = $product->id;
$product_id = $product_ident;
$woocommerce->cart->add_to_cart($product_id);
}
The thing is, nothing happens.
And my guess is that add_action( 'init', 'add_product_to_cart' );
gets stuck on something, or this isn’t the right hook to use.
I am using this hook to wait after woocommerce is done loading.
Yet I’m not sure if this does what I think it does.
So what am I doing wrong here? I got the code from WooThemes:
https://docs.woothemes.com/document/automatically-add-product-to-cart-on-visit/
You just have to use like this: