Add Product to Cart if Cart Empty Woocommerce

Add Product to Cart if Cart Empty Woocommerce
534 Views
0
(0)

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

How useful was this blog?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

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

  • CodexCoach

    - Web Development Expert

    CodexCoach is a skilled tech educator known for easy-to-follow tutorials in coding, digital design, and software development. With practical tips and interactive examples, CodexCoach helps people learn new tech skills and advance their careers.

Leave a comment

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