How to correctly set products in WooCommerce Cart

It’s critical to mimic WooCommerce’s core behavior as closely as possible, when you are making chances to the WooCommerce cart programmatically.

While developing Reserved Stock Pro for WooCommerce discovered that some of the popular plugins in the following categories may look over the important steps during the WooCommerce cart flow.

  • Side cart plugins
  • Mini cart plugins
  • product add-on plugins
  • product bundle plugins
  • Themes adding cart functionality

This includes incorporating the core hooks and filters into your code where they are necessary. Failing to do so can disrupt the cart and checkout flow, particularly when third-party plugins and developers depend on the standard process.

How to validate if a product can be added to the cart

Before attempting to add a product to the cart, you must ensure that the product passes validation checks. This is a crucial step to prevent issues that may arise if the product is not suitable for addition due to various reasons such as stock availability, user purchase limits, or other business rules.

Here’s how to validate a product:

$product_id = 123; // Replace with the actual product ID
$quantity = 2; // Replace with the desired quantity

$product = wc_get_product( $product_id );
if ( !$product ) {
    // Product does not exist
    return false;
}

$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );

if ( $passed_validation ) {
    // Product can be added to the cart
    WC()->cart->add_to_cart( $product_id, $quantity );
} else {
    // Product can't be added to the cart
    // Handle the error accordingly
}

Code language: PHP (php)

Never update the product stock directly

Directly changing a product’s stock quantity in the cart is not advisable. Before making any adjustments, you must verify whether the change will be accepted. This ensures the integrity of stock management and prevents conflicts with other plugins or extensions that may be monitoring stock levels.

Simply setting the the stocks on product is not enough for solid WooCommerce integration.

// Setting the quantity without validation is not enough
WC()->cart->set_quantity( $cart_item_key, $new_quantity );Code language: PHP (php)

Consider the following example where setting the quantity alone is insufficient:


$new_quantity = 3; // Replace with the new desired quantity

// Perform validation first, then notify third-parties using the core `woocommerce_update_cart_validation` filter

$passed_validation = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $cart_item, $new_quantity );

if ( $passed_validation ) {
    $updated = WC()->cart->set_quantity( $cart_item_key, $new_quantity );

    // Notify third-parties of the update
    $updated = apply_filters( 'woocommerce_update_cart_action_cart_updated', $updated );

    if ($updated) {
        // Stock in cart was updated successfully.
    } else {
        // Stock update failed, handle accordingly.
    }
} else {
    // Validation failed, handle accordingly.
}Code language: PHP (php)

By adhering to these best practices, you ensure that your customizations work seamlessly with WooCommerce’s core functionality and that compatibility with other plugins is maintained.

Always remember to test your changes thoroughly in a staging environment before deploying them to a live site.

Trigging a WooCommerce Cart update

I’ve found some third-party themes forget to update their custom carts with WooCommerce fragments.

Cart Fragments are used to update the cart via AJAX (without reloading the page).

The below jQuery event’s should be triggered for different cart & checkout actions.

As an example Reserved Stock Pro will also trigger the following JavaScript event once the countdown has finished. This ensures all cart products, calculations and taxes are updated.

jQuery( document.body ).trigger( 'wc_fragment_refresh');
jQuery( document.body ).trigger( 'wc_update_cart');
jQuery( document.body ).trigger( 'update_checkout');
jQuery( document.body ).trigger( 'updated_wc_div');Code language: JavaScript (javascript)

These events will normally trigger the cart & checkout to refresh using AJAX and grab the new cart content (using fragments). It’s necessary that your theme uses cart fragments for the cart, mini-cart or slide-out cart to be refreshed using these events.

Otherwise, the customer will continue to see their old cart contents after their reservations have expired. Customers would only know the products have been removed when they reload the page or load another page.

Check the WooCommerce Github

You should always go directly to the source code to see how WooCommerce handles carts & products.

Is your theme not working with WooCommerce cart fragments? Send your theme developer the official fragment code example and core from WooCommerce.

Avatar photo
Morgan

I help eCommerce store owners to run their stores smoothly and get more sales. Let's discuss optimizing your store! Hit me up via the support page or on Twitter @morganhvidt