How to add a product to a shopping cart programmatically in woocommerce

The problem
Sometimes you need the functionality of a shopping cart without forcing your customer to interact with your web site in the traditional way of a e-commerce.

For example let’s say you have a sample product that you just want automatically added to a shopping cart, so your customers can just click on let say “try product” and then be taken directly to a checkout process. This only applies to woocommerce, however the approach may be similar to other e-commerce toolkits.

This example is a modification from the woocommerce documentation.

Requirements:

# Requirement detail

1

A Product x is automatically added to a shopping cart when a non-logged in customer visits your site. This forces a visitor to register when they do checkout

2

Remove a product if the users is logged in

3

The site “try now” button is a link to “check out”, where the web site collects customers billing/shipping information.

These requirements allow a web site to collect customer billing information taking advantage of the built-in woocommerce logic.

Implementation:

  1. Go to your wordpress admin page usually under https://[your-web-site]/wp-admin/

  1. We are going to use the SKU to do a lookup in this case is L3-670115

  1. When your customers visit your site the product is going to be in their shopping cart , ready to checkout

  2. And here is the code, this needs to be visible in your functions.php file. But that you already knew it.
  3. add_action(‘wp_loaded’, ‘add_product_to_cart’);

    function add_product_to_cart()
    {

    if (!is_admin()) {

    $product_id = wc_get_product_id_by_sku(‘L3-670115’);

    $found = false;

    if (is_user_logged_in()) {
    if (sizeof(WC()->cart->get_cart()) > 0) {
    foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
    $_product = $values[‘data’];
    if ($_product->id == $product_id)
    WC()->cart->remove_cart_item($cart_item_key);
    }
    }
    } else {
    if (sizeof(WC()->cart->get_cart()) > 0) {
    foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
    $_product = $values[‘data’];
    if ($_product->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);
    }
    }
    }
    }

    Hope you enjoy.

Leave a Reply

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