I have two WooCommerce products and I want one of them loaded into the cart automatically when page A loads, and the other one loaded into the cart automatically when page B loads. My code checks the page ID and adds a specific product to the cart by product ID (after emptying the cart). Checkout is added via shortcodes to each page.
My problem is that regardless of whether I load page A or page B, when I get to the checkout I see the same product; the first product.
add_action( 'wp', 'bbloomer_add_product_to_cart_on_page_id_load' );
function bbloomer_add_product_to_cart_on_page_id_load() {
// product ID to add to cart
$product_id = 1150;
$product_id2 = 4792 ;
if ( is_page( 3337 ) ) {
WC()->cart->empty_cart();
WC()->cart->add_to_cart( $product_id );
}
else if ( is_page( 4232 ) ) {
WC()->cart->empty_cart();
WC()->cart->add_to_cart( $product_id2 );
}
}