Add code to your child theme’s functions.php file or use a plugin, such the Code Snippets plugin, that supports adding custom functions. Avoid explicitly adding custom code to the functions.php file of your parent theme because this will be completely overwritten when you update the theme.
We can add product to WooCommerce cart using add_to_cart() function with $product_id.
<?php
/**
* Cxc Automatically add product to cart
*/
add_action( 'template_redirect', 'cxc_woocommerce_add_product_to_cart' );
function cxc_woocommerce_add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 10; // Product ID
$cxc_found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data' ];
if ( $_product->get_id() == $product_id )
$cxc_found = true;
}
if ( ! $cxc_found ){
WC()->cart->add_to_cart( $product_id );
}
} else {
WC()->cart->add_to_cart( $product_id );
}
}
}
?>
Cxc Add another product depending on the cart total
<?php
/**
* Cxc Add another product depending on the cart total WooCommerce
*/
add_action( 'template_redirect', 'cxc_woocommerce_add_product_to_cart' );
function cxc_woocommerce_add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 10; // Product ID
$cxc_found = false;
$cart_total = 300; //replace with your cart total
if( $woocommerce->cart->total >= $cart_total ) {
//check if product already in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$cxc_found = true;
}
if ( ! $cxc_found ){
$woocommerce->cart->add_to_cart( $product_id );
}
} else {
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
}
?>