Search code examples
phpajaxwordpresswoocommercecart

Refresh a custom component on cart events in Woocommerce


I have a component called cart checkout that is displayed on a the woocommerce archive-product.php page. When someone clicks add to card on one of the products on this page I want this component to update to show the amount of items, the name and the price. I am currently using the following code to display this information, but you have to refresh the page to see it updated after hitting add to cart.

<div class="cart-wrap">
    <p class="cart-title">Currently in Cart</p>
    <?php
        global $woocommerce;
        $items = $woocommerce->cart->get_cart();

            foreach($items as $item => $values) { 
                $_product =  wc_get_product( $values['data']->get_id()); 
                echo "<p>" . $_product->get_title().'<span class="amount"> x '.$values['quantity']; 
                $price = get_post_meta($values['product_id'] , '_price', true);
                echo " $".$price."</span></p>";
            } 
    ?>
    <a class="cart-checkout" href="<?php echo wc_get_cart_url(); ?>" >Checkout</a>
</div>

I want to use ajax I would assume but don't even know where to start to figure out how to get it to work.

Ok thanks ahead of time.


Solution

  • To ajaxify cart components (or called in Woocommerce fragments), you will use the following:

    1) your revisited code component:

    <div class="cart-wrap">
        <p class="cart-title"><?php _e("Currently in Cart", "woocommerce"); ?></p>
        <div id="cart-items-wrap">
        <?php
            foreach( WC()->cart->get_cart() as $cart_item ) {
                printf( '<p>%s<span class="amount"> x %s %s</span></p>',
                    $cart_item['data']->get_title(),
                    $cart_item['quantity'],
                    wc_price( wc_get_price_to_display( $cart_item['data'] ) )
                );
            }
        ?>
        </div>
        <a class="cart-checkout" href="<?php echo wc_get_cart_url(); ?>"><?php _e("Checkout", "woocommerce"); ?></a>
    </div>
    

    2) The hooked function that will ajax refresh your component:

    add_filter( 'woocommerce_add_to_cart_fragments', 'ajaxify_components', 10, 1 );
    function ajaxify_components( $fragments ) {
        ob_start();
        ?>
        <div id="cart-items-wrap">
        <?php
            foreach( WC()->cart->get_cart() as $cart_item ) {
                printf( '<p>%s<span class="amount"> x %s %s</span></p>',
                    $cart_item['data']->get_title(),
                    $cart_item['quantity'],
                    wc_price( wc_get_price_to_display( $cart_item['data'] ) )
                );
            }
        ?>
        </div>
        <?php
        $fragments['#cart-items-wrap'] = ob_get_clean();
    
        return $fragments;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.