Skip to content

Instantly share code, notes, and snippets.

@andrejcremoznik
Created April 14, 2021 13:08
Show Gist options
  • Save andrejcremoznik/a772656fb948033afc8be0de76443fbb to your computer and use it in GitHub Desktop.
Save andrejcremoznik/a772656fb948033afc8be0de76443fbb to your computer and use it in GitHub Desktop.
What are WooCommerce add to cart fragments? (to the point tl;dr Woo ajax tutorial)

WooCommerce has an option to run various UI actions via ajax.

If you are developing a theme and want to update your own elements during Woo ajax calls you will want to add the following hook:

add_filter('woocommerce_add_to_cart_fragments', 'my_woocommerce_add_to_cart_fragments');

function my_woocommerce_add_to_cart_fragments($fragments) {
  $fragments['#my-dom-element'] = '<div id="my-dom-element">Some new markup with some computed value.</div>';
  return $fragments;
}

In the hooked function add a new key to the array:

  • the key is an element selector and will be directly passed to jQuery()
  • the value is an HTML string that will be directly passed to jQuery().replaceWith()

Make sure the HTML string contains the selector from the key, because the JS will replace the matching element with the new element. Basically it does this:

$.each(fragments, (key, value) => $(key).replaceWith(value))
@andrejcremoznik
Copy link
Author

How to show and update the mini-cart (real use case):

add_filter('woocommerce_add_to_cart_fragments', 'my_woocommerce_add_to_cart_fragments');

function my_woocommerce_add_to_cart_fragments($fragments) {
    global $woocommerce;
    ob_start();
    woocommerce_mini_cart();
    $mini_cart = ob_get_clean();
    $fragments['#my-mini-cart'] = sprintf(
        '<div class="mini-cart" id="my-mini-cart">
            <a class="mini-cart__trigger" href="%s" title="%s">
                <span class="mini-cart__qty">%d</span>
                <i class="mini-cart__ico fas fa-shopping-cart"></i>
            </a>
            <div class="mini-cart__content">%s</div>
        </div>',
        wc_get_cart_url(),
        esc_html__('View your shopping cart', 'my-theme'),
        $woocommerce->cart->cart_contents_count,
        $mini_cart
    );
    return $fragments;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment