Add Product to Cart Programmatically Woocommerce

Add Product to Cart Programmatically Woocommerce
4118 Views
4
(657)

If you wish to add a product to the cart programmatically in WooCommerce, you can do so by adding an action hook and a callback function containing the logic to do so.

We can add product to WooCommerce cart using add_to_cart() function with $product_id.

<?php
add_action( 'wp', 'cxc_woocommerce_add_product_to_cart' );
function cxc_woocommerce_add_product_to_cart() {
	$product_id = 10; // product ID to add to cart
	WC()->cart->empty_cart();
	WC()->cart->add_to_cart( $product_id ); 
}
?>

Code goes in function.php file of your active child theme (or active theme).

Alternative solutions

<?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 );
			}
		}
	}
}
?>

How useful was this blog?

Click on a star to rate it!

Average rating 4 / 5. Vote count: 657

No votes so far! Be the first to rate this blog.

Leave a comment

Your email address will not be published. Required fields are marked *