• Resolved MarceloCS

    (@marcelocs)


    Hi!

    Is it possible to make the automatic add to cart function work only in certain page? Ie: when certain page is visited a product is add to cart.

    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi, MarceloCS, I’m another WooCommerce user.

    Building off of the example provided at https://docs.woocommerce.com/document/automatically-add-product-to-cart-on-visit/, here is some code you may use to do this:

    /**
     * Automatically add product to cart on visit
     */
    add_action( 'template_redirect', 'add_product_to_cart' );
    function add_product_to_cart() {
    	if ( is_page(121) ) { //use page id here 
    		$product_id = 64; //replace with your own product id
    		$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 )
    					$found = true;
    			}
    			// if product not found, add it
    			if ( ! $found )
    				WC()->cart->add_to_cart( $product_id );
    		} else {
    			// if no products in cart, add it
    			WC()->cart->add_to_cart( $product_id );
    		}
    	}
    }

    Page ID can be found by looking at the page URL when editing a certain page, ex:
    https://example.com/wp-admin/post.php?post=1043&action=edit – 1043 is the page ID.

    Product ID can be found by going to the Products -> All Products menu in the WordPress admin and hovering over the product name.

    Thread Starter MarceloCS

    (@marcelocs)

    Worked perfectly. Thank you very much, Ian Sackofwits!

    Plugin Support abwaita a11n

    (@abwaita)

    Glad to hear it – thanks for letting us know!

    I’ll mark this thread as resolved now. If you have any further questions, I recommend creating a new thread.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘automatic add to cart in certain page’ is closed to new replies.