woocommerce add to cart code example
Example 1: add_to_cart how to call it woocommerce
add_action( 'template_redirect', 'quadlayers_add_to_cart_function' );
function quadlayers_add_to_cart_function () {
$product_id = 1326;
if ( WC()->cart->get_cart_contents_count() == 0 ) {
WC()->cart->add_to_cart( $product_id );
}
}
Example 2: woocommerce apply coupon with add to cart
function wc_ninja_apply_coupon( $coupon_code ) {
if ( 'test_code' === $coupon_code ) {
$product_id = 99;
WC()->cart->add_to_cart( $product_id );
}
}
add_action( 'woocommerce_applied_coupon', 'wc_ninja_apply_coupon' );
Example 3: add a item to cart woocomerce with quantity
WC()->cart->add_to_cart( 500, 5 );