I am using WooCommerce to create an online store and I want to automatically add a product to the cart when a visitor lands on a specific page. How can I achieve this functionality in WooCommerce? Is there a plugin or a code snippet that can do this? Thank you for your help.
I did something similar to your scenario before. Here is the modified version of that code.
add_action( 'template_redirect', 'auto_add_product_to_cart' );
function auto_add_product_to_cart(){
if ( is_page( $page_id ) ) {
// $product_ids = array();
// $args = array(
// 'post_type' => 'product',
// 'posts_per_page' => -1,
// 'meta_key' => '_add_product_to_cart',
// 'meta_value' => 'yes',
// );
// $loop = new WP_Query( $args );
// while ( $loop->have_posts() ) : $loop->the_post();
// global $product;
// $product_ids[] = get_the_ID();
// endwhile;
// wp_reset_query();
$product_ids = array(10, 12, 15);
// Check if the product is already in the cart
$cart_items = WC()->cart->get_cart();
if ( count( $cart_items ) > 0 ) {
// If product id is already in the cart, unset the product id
foreach ( $cart_items as $item_key => $item_values ) {
if ( ($key = array_search($item_values['data']->id, $product_ids)) !== false ){
unset($product_ids[$key]);
}
}
// Add the rest of the product ids to the cart
if ( count($product_ids) > 0 ) {
foreach ( $product_ids as $product_id ) {
WC()->cart->add_to_cart( $product_id );
}
}
}
else {
//If no products are in the cart, add it
foreach ($product_ids as $product_id) {
WC()->cart->add_to_cart( $product_id );
}
}
}
}
You can use WP_Query
to get the products to add to the cart (which I used in my case) or You can use product ID below to add those products to the cart.
$product_ids = array(10, 12, 15);
For more info visit woocommerce official page.