Search code examples
phpjquerywordpresswoocommercesession-storage

Show WooCommerce cart count outside of Wordpress


I have a full website that I've built already. I have now installed Wordpress in a subdirectory (/shop) and I'm using WooCommerce to power the sale of products.

In the top menu bar while in the shop page I have a cart icon showing the number of products in the cart.

I would like that when the user clicks back into the non-Wordpress pages of the site to continue showing the number of items in the cart. Can someone point me in the right direction? I have tried to include the main class-woocommerce.php class but it's not working.

Here's what I have been using to test in my index.php file:

include 'shop/wp-content/plugins/woocommerce/includes/class-woocommerce.php';
global $woocommerce;
var_dump($woocommerce->cart);

EDIT:

I have now included wp-load.php instead of the class-woocommerce.php and when I dump the WooCommerce cart I can see it but it's completely empty, ie has 0 items even though I had items placed in the cart.


Solution

  • Update:

    This could be done also setting a custom cookie or better using javascript session storage this way:

    add_action('wp_footer', 'custom_cart_item_count_script');
    function custom_cart_item_count_script(){
        if( WC()->cart->is_empty() )
            $cart_count = 0;
        else
            $cart_count = WC()->cart->get_cart_contents_count();
    
        if(isset($cart_count)){
        ?>
            <script type="text/javascript">
                jQuery(function($){
                    var cartCount = <?php echo $cart_count; ?>,
                        csName = 'CARTCOUNT',
                        csStorage = sessionStorage.getItem(csName);
    
                    if(csStorage == null || csStorage == 'undefined'){
                        sessionStorage.setItem(csName, cartCount);
                        console.log(sessionStorage.getItem(csName));
                    }
                });
            </script>
        <?php
        }
    }
    

    This code goes in function.php file of your active child theme (or active theme).

    Tested and works.


    On your non Wordpress pages:

    You will need to get this browser session storage value. so you will add something like the following in your non Wordpress pages:

    ?>
        <script type="text/javascript">
            jQuery(function($){
                var caName = 'CARTCOUNT',
                    caStorage = sessionStorage.getItem(caName);
    
                if(caStorage == null || caStorage == 'undefined')
                    $('span.cart-count').html('0');
                else
                    $('span.cart-count').html(caStorage);
    
                console.log('css-read: '+caStorage);
            });
        </script>
        <p>Cart count: <span class="cart-count"></span></p>
    <?php
    

    Tested and works: