Coding Notes WordPress

Force Item To Add To Cart On Page Load In WordPress WooCommerce Cart

This probably isn’t useful for anyone but I’m currently using WooCommerce with WordPress and I needed a solution where a product item would automatically be added to cart on page load.

The code below is what I came up with, this code will also force the user to have only 1 quantity of the item.

To use, fill in the $product_id variable with your product id and paste the code in your child themes functions.php file.

add_action( 'wp_loaded', function() {
  $product_id = 1;
  
  if ( defined( 'WC_PLUGIN_FILE' ) ) {
    if ( class_exists( 'WooCommerce' ) ) {
      if ( ! function_exists( 'WC' ) ) {
        $GLOBALS['woocommerce'] = WooCommerce::instance();
      }
      
      if ( method_exists( $GLOBALS['woocommerce']->cart, 'add_to_cart' ) ) {
        $wc = $GLOBALS['woocommerce'];
        
        $alreadyIn = false;
        
        foreach ( $wc->cart->get_cart_contents() as $cartItem) {
          // force user to only have 1 quantity
          if ( $cartItem['product_id'] == $product_id && $cartItem['quantity'] > 1 ) {
              $wc->cart->set_quantity( $cartItem['key'], 1 );
          }
          
          if ( $cartItem['product_id'] == $product_id ) {
            $alreadyIn = true;
            break;
          }
        }
        
        if ( ! $alreadyIn ) {
          $wc->cart->add_to_cart( $product_id, 1 );
        }
      }
    }
  }
}, 9999 );

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.