How To Get Cart Items In Woocommerce

How to Get Cart Items in WooCommerce: A Beginner’s Guide

So, you’re diving into the world of WooCommerce development and want to know how to access the items in a user’s cart. Understanding how to get cart items in WooCommerce is fundamental for many things, from displaying a custom cart summary to creating advanced shipping calculations or even personalizing the user experience. Don’t worry, it’s not as complicated as it sounds! This guide will walk you through the process with simple explanations and practical examples.

Why Access Cart Items? Real-World Scenarios

Imagine these scenarios:

    • Custom Cart Summary: You want to display a more detailed cart summary than the default WooCommerce widget, showing product images, specific discounts, or even a “You’re almost there!” message if they reach a certain spending threshold.
    • Conditional Shipping: You need to calculate shipping costs based on the *type* of items in the cart. For instance, you might offer free shipping on fragile items over a certain value, but not on heavier, non-fragile items.
    • Personalized Recommendations: You want to suggest related products based on what’s already in the user’s cart. If they have coffee beans in their cart, you could recommend coffee filters or a new mug.
    • Inventory Management: You need to integrate with an external inventory system to update stock levels in real-time as items are added to the cart.
    • Explore this article on How To Remove Default Sorting In Woocommerce

    In all of these cases, you need to access the cart items. Let’s see how it’s done.

    The Magic: The `$woocommerce` Global Object

    WooCommerce provides a global object called `$woocommerce`. This object is your key to accessing all sorts of WooCommerce functionality, including the cart. Inside this object, you’ll find the `$cart` property, which holds all the information about the current user’s cart.

    Important: This code will generally work within your theme’s `functions.php` file or a custom plugin. Ensure the WooCommerce plugin is active when you run the following code.

    Getting the Cart Object

    First, let’s get the cart object itself:

     global $woocommerce; $cart = $woocommerce->cart; 

    Now `$cart` contains all the information you need.

    Looping Discover insights on How To Make A Woocommerce Website Tutorials Through Cart Items

    The most common task is to loop through each item in the cart. You can do this using the `get_cart()` method.

     global $woocommerce; 

    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {

    $_product = apply_filters( ‘woocommerce_cart_item_product’, $cart_item[‘data’], $cart_item, $cart_item_key );

    $product_id = apply_filters( ‘woocommerce_cart_item_product_id’, $cart_item[‘product_id’], $cart_item, $cart_item_key );

    if ( $_product && $_product->exists() && $cart_item[‘quantity’] > 0 && apply_filters( ‘woocommerce_cart_item_visible’, true, $cart_item, $cart_item_key ) ) {

    // Now you can access product information!

    $product_name = $_product->get_name();

    $quantity = $cart_item[‘quantity’];

    $product_permalink = $_product->get_permalink( $cart_item );

    echo ‘Product Name: ‘ . $product_name . ‘
    ‘;

    echo ‘Quantity: ‘ . $quantity . ‘
    ‘;

    echo ‘Link: ‘ . $product_name . ‘
    ‘;

    }

    }

    Let’s break down what’s happening:

    • `$woocommerce->cart->get_cart()`: This retrieves an array of all the items in the cart. Each item is represented as an array containing information about the product and its quantity.
    • `foreach` loop: This loops through each item in the cart.
    • `$cart_item_key`: This is a unique key that identifies the cart item.
    • `$cart_item`: This is an array containing all the information about the cart item, including the product data and quantity.
    • `$_product = apply_filters(…)`: This is a crucial step! It gets the actual `WC_Product` object (representing the product itself) from the `$cart_item[‘data’]`. The `apply_filters` ensures compatibility with other plugins and customizations. This also filters the product so that it can be modified by other plugins.
    • `$product_id = apply_filters(…)`: This gets the product ID. Again, using `apply_filters` is best practice.
    • `$_product->get_name()`: This gets the name of the product.
    • `$cart_item[‘quantity’]`: This gets the quantity of the product in the cart.
    • `$_product->get_permalink()`: This gets the product’s URL.
    • Conditional Checks: These checks ensure the product exists, is in stock, and is visible.

    Accessing Specific Product Information

    Inside the loop, you can access a wealth of information about each product using the `$cart_item` array and the `$_product` object. Here are some examples:

    • Product ID: `$product_id` (as shown above)
    • Price: `$_product->get_price()`
    • Featured Image URL: `get_the_post_thumbnail_url( $product_id )`
    • Product SKU: `$_product->get_sku()`
    • Product Categories: `wc_get_product_category_list( $product_id )`

    Remember to consult the WooCommerce documentation for a complete list of available methods and properties on the `WC_Product` object.

    Example: Displaying a Custom Cart Summary

    Let’s put it all together with a simple example of displaying a custom cart summary:

     function custom_cart_summary() { global $woocommerce; 

    echo ‘

    Your Cart Summary

    ‘;

    if ( empty( $woocommerce->cart->get_cart() ) ) {

    echo ‘

    Your cart is empty.

    ‘;

    return; // Exit the function if the cart is empty

    }

    echo ‘

      ‘;

      foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {

      $_product = apply_filters( ‘woocommerce_cart_item_product’, $cart_item[‘data’], $cart_item, $cart_item_key );

      $product_id = apply_filters( ‘woocommerce_cart_item_product_id’, $cart_item[‘product_id’], $cart_item, $cart_item_key );

      if ( $_product && $_product->exists() && $cart_item[‘quantity’] > 0 && apply_filters( ‘woocommerce_cart_item_visible’, true, $cart_item, $cart_item_key ) ) {

      $product_name = $_product->get_name();

      $quantity = $cart_item[‘quantity’];

      $product_price = $_product->get_price();

      $product_image_url = get_the_post_thumbnail_url( $product_id, ‘thumbnail’ ); //Get Thumbnail size image

      echo ‘

    • ‘;

      echo ‘' . $product_name . '‘;

      echo ‘‘ . $product_name . ‘

    • Quantity: ‘ . $quantity . ‘
    • Price: $’ . $product_price;

      echo ‘

    • ‘;

      }

      }

      echo ‘

    ‘;

    echo ‘

    Total: $’ . $woocommerce->cart->get_cart_total() . ‘

    ‘; //Display the total cart amount

    }

    // Hook the function to display the summary (e.g., in your theme’s template)

    add_action( ‘woocommerce_before_cart’, ‘custom_cart_summary’ );

    This code creates a function `custom_cart_summary()` that:

    • Displays a heading “Your Cart Summary”.
    • Checks if the cart is empty and displays a message if it is.
    • Loops through each item in the cart.
    • Retrieves the product name, quantity, price and thumbnail image.
    • Displays this information in a list.
    • Displays the total cart amount.
    • Hooks this function to the `woocommerce_before_cart` action, which will display the summary *before* the default WooCommerce cart.

    Where to put this code: You’d typically place this code in your theme’s `functions.php` file, or in a custom plugin.

    Key Takeaways

    • Use the `$woocommerce` global object to access the cart.
    • Use `$woocommerce->cart->get_cart()` to get an array of cart items.
    • Loop through the cart items using a `foreach` loop.
    • Use `$_product = apply_filters(…)` to get the `WC_Product` object for each item.
    • Use the `WC_Product` object to access product information like name, price, and image.
    • Remember to use `apply_filters` for compatibility and best practices.

By following these steps, you’ll be well on your way to mastering how to get cart items in WooCommerce and creating amazing custom features for your online store. Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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