Redirect Empty Cart to Home and Checkout to Cart

So we needed an option to redirect empty cart to home. This besides the cart skip redirects we already had. I check out a few solutions with our current code base setup.

One by Etzel Storfer Web Development :

// ===========================================================================
//  Redirect Empty Checkout to Home 
// ===========================================================================

add_action('template_redirect', 'redirection_function');

function redirection_function(){
    global $woocommerce;

    if( is_checkout() && 0 == sprintf(_n('%d', '%d', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count) && !isset($_GET['key']) ) {
        wp_redirect( home_url() ); 

which did not work as checkout still went to cart and cart back to checkout. Another option which is quite similar:

add_action("template_redirect", 'redirection_function');
function redirection_function(){
   global $woocommerce;
   if( is_cart() && WC()->cart->cart_contents_count == 0){
       wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );

had the same result. Redirects kept on going as it did not overcome current ones set up.

Enhancing Existing Redirect

This was because an existing redirect to checkout when cart was hit. The solutions were not bad at all. They just did not work in our setup. So I tweaked the code for to make an exception when an empty cart was there. This by adding

if( is_cart() && WC()->cart->cart_contents_count == 0) {
        wp_redirect( home_url() ); 
    else {

to an existing method that made it this in the end:

// Global redirect to check out when hitting cart page unless cart empty
add_action( 'template_redirect', 'redirect_to_checkout_if_cart' );
function redirect_to_checkout_if_cart() {

    if ( !is_cart() ) return;
    global $woocommerce;

    // Getting the checkout for the current language.
    // Checking whether icl_object_id() exists as a
    // function since its not a WordPress or theme function.

    if( is_cart() && WC()->cart->cart_contents_count == 0) {
        wp_redirect( home_url() ); 
    else {
        $current_language_checkout_url = ! function_exists( 'icl_object_id' ) ? get_permalink(
        ) : $woocommerce->cart->get_checkout_url();

        wp_redirect( $current_language_checkout_url, '301' );


So this means you could very well use one of the two earlier mentioned functions just fine. I just needed it integrated in an earlier set up method.

GDPR WooCommerce Checklist

To comply with the GDPR or General Data Protection Regulation which will come into force this 25th of May 2018 we have come up with a GDPR WooCommerce Checklist. One you can use to go through your website and or business setup to decide what you need to do. We will start with a general introduction and then move on to the checklist


The GDPR has been in the making for a long time already. It was adapted in the EU parliament on April 2016 as a matter of fact. It was set up to protect the privacy of EU citizens and guarantee a proper way of dealing with personal data. And as stated above it will come into effect May 26th 2018. So you must have heard about it and wondered about it. And perhaps you have sorted things already. Still good to go through this article a bit too.

Parties Concerned

It applies to all business within the EU and to all businesses doing business with customers or partners within the EU that collect personal data from customers within the EU to be precise. What is personal data? Here from the horse’s mouth

Any information related to a natural person or ‘Data Subject’, that can be used to directly or indirectly identify the person. It can be anything from a name, a photo, an email address, bank details, posts on social networking websites, medical information, or a computer IP address.

So this means this new GDPR setup will be applicable to many businesses throughout the world. Many of us work with clients in the EU and collect data to identify clients. Especially if you run ecommerce like many of our customers who run WooCommerce. So therefore probably need to play ball here.

Non Compliance Fines

According to the source of the regulation, the EU, you might not want to not participate because:

Organizations can be fined up to 4% of annual global turnover for breaching GDPR or €20 Million. This is the maximum fine that can be imposed for the most serious infringements e.g.not having sufficient customer consent to process data or violating the core of Privacy by Design concepts. There is a tiered approach to fines e.g. a company can be fined 2% for not having their records in order (article 28), …….

Each member state will set up its own supervisory authority to make sure these regulations are followed and will penalize those who do not. See also WPMU’s article on this.

FAQ Page source

Site Checklist

Here is a short summary or checklist first based on a WooCommerce article from December last year. One with some tweaks. And then some more details bits and pieces.

  • Tell the user who you are, why you collect the data, for how long, and who receives it.
  • Get a clear consent [when required] before collecting any data.
  • No race, religion or sexual preference data can be stored
  • No checkboxes asking for personal information can be checked in advance
  • Let users access their data, and take it with them.
  • Let users delete their data.
  • Let users know if data breaches occur.

Privacy Policy and Terms & Conditions

You will need a privacy policy that clearly indicates what data you collect and how.  The WooCommerce Point of Sale Plugin has a solid one. And decent terms and conditions as well. Do go through them and adjust them properly, preferably with your lawyer before using them on your own site though. Terms and conditions are important here as you are required to have certain security measures in place and these need to be reflected in the Terms & Conditions.

Useful Plugins

Based on the WordPress Plugins repo GDPR Tag I found a couple of useful plugins:

Delete Me Plugin

We are not using this one yet as removing someone is a big step. We will make sure clients will be deleted when they want to promptly and will remove inactive customers after an x amount of time. Like with all data, it should not be stored without need and so needs to be removed when an account is inactive for a long time or is requested to be removed. However, we are following the online blogging sphere for more information on this so may update details on the right to be forgotten.

WP GDPR Compliance Plugin

WP GDPR Compliance is an amazing plugin that will either set up the needed checkboxes and or texts when possible for (order) forms like Gravity Forms and …. WooCommerce order forms or will give you tips and or warnings how to do things. It will for example tell you add a consent box on order forms using their checklist:

Make sure you add a checkbox specifically asking the user of the form if they consent to you storing and using their personal information to ship the order. This cannot be the same checkbox as the Privacy Policy checkbox you should already have in place. The checkbox must be unchecked by default. Also mention if you will send or share the data with any 3rd-parties and which.

And you can activate this for WooCommerce:

WooCommerce GDPR Checkbox

This can be done for Gravity Forms and Contact Form 7 too. It also tells you to turn off Jetpack comments if you do. This as they do not seem to have an option to opt-in and understand they share some personal info commenting – See WP Tavern article on this. Once turned off you can add a consent checkbox with the plugin:

Comment Form GDPR Compliance

Cookie Bot vs Responsive Cookie Consent vs Cookie Consent

GDPR Compliance plugin does not help with the cookie banner most of you use already. A banner to ask for consent to use cookies. For that you can try Cookiebot. You will have to sign up though . If you do not want that you can use responsive cookie consent or Cookie Consent one. I prefer the latter one. No need to sign up for something extra and it is well maintained and used a lot. It also sets up a cookie explanation page.

Responsive Cookie Consent

Google Analytics and GDPR

You need to update your site’s Privacy Policy to cover all personal information that is being collected through your site. You also need to adjust your Google Analytics settings to comply with these new rules:

If you have a business established in the territory of a member state of the European Economic Area or Switzerland or you are otherwise subject to the territorial scope of the General Data Protection Regulation (GDPR), and if you have entered into a direct customer contract with Google to use Google Analytics, then you are eligible to accept the Google Ads Data Processing Terms. Learn more

You can also setup the period of time you store the data. See some details on howto at .

Google Analytics Data Retention

26 months is set up automatically if you agreed with the new GDPR rules:

Analytics Default retention

Jef makes a good point in the comments at SE Roundtable:

The point is… (Technically) With GDPR, you’re supposed to only keep user data you’re using. If you’re storing data about users, you have to have a good reason to keep it. Just having it in Google Analytics for “reporting purposes” isn’t a good enough reason either.

Obviously, they’re making these tools to hopefully take the heat off themselves, and thus reduce the risk across the board for their customers.

I think most medium sized companies can export the data they care about, anonymize it and/or aggregate it to the levels they need, and let Google handle the regular dumping of data they don’t need.

So you should keep data only if you have a good reason to use them and once that is done you should remove the data. Also you need to ask for consent so you need the cookie plugin to do this for you.

Article still developing ..

Custom Customer Processing Order Message

Sometimes you need to add a custom Customer Processing Order message to your email template for your clients. This so you send them additional instructions. In WooCommerce the basic email editing options are rather unlimited. Not to worry though. There are options.

Initial Trial

You can add the following action hook to the functions.php file of your theme or child theme:

add_action( 'woocommerce_email_before_order_table','add_order_email_instructions', 10, 4 );
function add_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {
    if ( 'customer_processing_order' == $this->id && ! $sent_to_admin ) {
        echo 'Your login details are on their way. (They may take up to 10 minutes to arrive in your inbox.';

Snippet based on Helga the Viking’s code at SO.


It (the code snippet / action hook) tells WooCommerce to add an extra Custom Customer Processing Order Message to the customer processing order email.You could just add the message to all outgoing emails by WooCommerce and drop the if statement. Or you could go for another email template where you would like to add code to. It is all possible really.

NB The actual action is added to email-order-details.php as well as some other payment gateway files.

Object Snag

With the mentioned action you will however get this error:

2018-02-19T22:31:46+00:00 CRITICAL Uncaught Error: Using $this when not in object context in /srv/www/
Stack trace:
#0 /srv/www/ add_order_email_instructions(Object(WC_Order), true, false, Object(WC_Email_New_Order))
#1 /srv/www/ WP_Hook->apply_filters('', Array)
#2 /srv/www/ WP_Hook->do_action(Array)
#3 /srv/www/ do_action('woocommerce_ema...', Object(WC_Order), true, false, Object(WC_Email_New_Order))
#4 /srv/www/ include('/srv/www/publiq...')
#5 /srv/www/

This is because  you can’t use $this outside of the class definition. But with the $email object added this should not occur. And that is available since WooCommerce 2.5+. You just need it as a parameter too. Well, as you will see things changed somewhat in WC 3+ and another object->property is needed.

WooCommerce 3+ Updated Trial

So with WooCommerce 3+ I then thought I needed:

add_action( 'woocommerce_email_before_order_table','add_order_email_instructions', 10, 4 );
function add_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {
if ( 'customer_processing_order' == $order->get_id() && ! $sent_to_admin ) {
echo 'Your login details are on their way. (They may take up to 10 minutes to arrive in your inbox.';

with $order->get_id() as I otherwise still had the same error. But the if statement did not do the trick properly.

Working Solution

The final best option is with changed if statement:

add_action( 'woocommerce_email_before_order_table','add_order_email_instructions', 10, 4 );
function add_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {
if ( $email->id == 'customer_processing_order' ) {
echo 'Your login details are on their way. (They may take up to 10 minutes to arrive in your inbox.';

So $email->id == ‘customer_processing_order works. Result:

Order being processed custom message

WooCommerce 3.0+ Single Product Image Zoom & Link Removal

Sometimes you want to do a Single Product Image Zoom & Link Removal. You just do not need the zoom effect nor do you want the image to link to the original size image. Well there are WooCommerce filters for that

Product Image Zoom Removal

To remove the product thumbnail zoom effect you can use the following filter:

function custom_single_product_image_html( $html, $post_id ) {
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
return get_the_post_thumbnail( $post_thumbnail_id, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ) );
add_filter('woocommerce_single_product_image_thumbnail_html', 'custom_single_product_image_html', 10, 2);

It basically uses the woocommerce_single_product_image_thumbnail_html filter (see file at Github)to manipulate the product thumbnail. Instead of returning the html with zoom options it just returns:

get_the_post_thumbnail( $post_thumbnail_id, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ) );

which is just the shop single large product thumbnail.

Product Image Link Removal

The product link is removed with this same function as well as you have now completely replaced the html with just the thumbnail instead of a thumbnail that links to the original and has zoom capabilities. So we are now all done here!

Bonus: Quantity Button Removal

If you would like to remove the quantity button as you only sell your products individually and you do not allow more than one of each you can either lock this per product or use this filter:

 * @desc Remove in all product type
function wc_remove_all_quantity_fields( $return, $product ) {
    return true;
add_filter( 'woocommerce_is_sold_individually', 'wc_remove_all_quantity_fields', 10, 2 );

To do it per product

  • Edit your product.
  • Click “Inventory”.
  • Check the box that says “Sold Individually”

Disable a WooCommerce Payment Option

If you need to disable a WooCommerce Payment option because you realize you no longer needed or you need to turn of a default you mind have an initial tough time finding it. Once you know it is really easy though.

WooCommerce Checkout Payment Option

Just go to WooCommerce Settings > Checkout. This is where you will find all the possible checkout options such as PayPal, Stripe and so on.

WooCommerce Checkout Options

Just go ahead and go to the tab for the payment gateway you do not want to use anymore.

Payment Option Tab

So go to the payment option you would like to remove / disable. Then uncheck this option like we have done here below for the check payments. You can see there is no checkmark for the enable check payments. So this option is NOT in use for this WooCommerce store.

Uncheck WooCommerce Check Payments

Saving Changes

Do not forget to save your settings and or empty cache when need be. Otherwise you changes will not be stored nor displayed. To make sure all worked well simulate a purchase and check that you do not see this payment option on the checkout anymore.

Problem with your Stripe Webhook

Sometimes you will get an email from Stripe telling you there is a problem with your Stripe Webhook. For some reason it fails. Either the web hook cannot be found somehow or it cannot be loaded properly.

Webhook url

You can find the webhook to be used in your WooCommerce settings > Checkout > Stripe . It should be something like . Copy it over into your Stripe Dashboard under webhooks should work just fine out of the box. This webhook can be used to:

  • Update a customer’s membership record in your database when a subscription payment succeeds
  • Email a customer when a subscription payment fails
  • Check out the Dashboard if you see that a dispute was filed
  • Make adjustments to an invoice when it’s created (but before it’s been paid)
  • Log an accounting entry when a transfer is paid

So really useful on giving feedback when payments fail. And that we had in our case. Wrote about that Stripe issue here.

Errors 404 – Webhook not found

We had the following error in our logs related to this

2018/01/24 21:56:44 [error] 16241#16241: *41904 upstream timed out (110: Connection timed out) while reading response header from upstream, client:, server: domain, request: "POST /?wc-ajax=checkout HTTP/2.0", upstream: "fastcgi://unix:/var/run/php-fpm-wordpress.sock", host: "", referrer: ""

and in the access log we found - - [25/Jan/2018:06:29:14 +0000] "POST /wp/wp-admin/admin-ajax.php?action=stripe_webhook HTTP/1.1" 400 11 "-" "Stripe/1.0 (+" "-"

So somehow the webhook was not found and so no 2xx response was given. And as Stripe mentions this is one of the most common mistakes using webhooks. The wrong url is entered.

Issue & Solution

In our case we had entered the wrong webhook url It should have been  as mentioned earlier. That caused it not to work and Stripe sending us an email with “Problem with your Stripe Webhook” in the title.

Stripe 402 Error – Payment Required

Setting up Stripe for a client on WooCommerce we ran into a Stripe 402 Error. So what does a 402 error mean and how can we solve this issue? Well Let’s get into the finer details shall we.

Stripe Environment

Keys used In our case this happened using a live publishable and private key. So this meant we had to use a real credit card and enter details properly. Sometimes people run test mode and forget to use a dummy credit card for testing or forget to turn on testing. So please do check what mode you are using and use the proper payment details.

Stripe 402 Code

When the payment does fail with a Stripe 402 error it means the payment went wrong.

Stripe 402 Error

I quote Stripe:

Not all errors map cleanly onto HTTP response codes, however. When a request is valid but does not complete successfully (e.g., a card is declined), we return a 402 error code. To understand why a card is declined, refer to the list of codes in the documentation.

So as there are multiple problems that can cause this error you need to find out what the error was you had. And for that you need to get the possible decline code.

Source of the Error

We can see in the page source  what the issue is once the payment is done. To view the source just after a failure use command+alt+i on Chrome on your Mac to open the inspector for this. Sometimes it is just the wrong credit card details entered. Again, check the decline code / message.

Also, when you have error message recording turned on you can check your WooCommerce system logs. These are located at /srv/www/  for those using Trellis. For others at wp-content/uploads/wc-logs. In our case we found:

01-24-2018 @ 13:54:48 - ====Start Log====
Error: stdClass Object
 [error] => stdClass Object
 [message] => Your card's security code is incorrect.
 [type] => card_error
 [param] => cvc
 [code] => incorrect_cvc
 [charge] => ch_111111111111111111111


So the client did not enter the proper security code or cvc. In other cases it could be an incorrect card number or something else related tot the payment.


Well, as soon as you have the decline code or error found in the source of the page or in your WooCommerce error logs or other payment logs you will be able to add details properly. As stated we had an issue with the cvc code. Once the client entered the proper security code the payment went through.



WooCommerce and Gutenberg – Great stuff ahead!

WooCommerce and Gutenberg.. What will happen when Gutenberg Editor gets introduced to your WooCommerce site in WordPress 5.0? Will it be Armageddon and will all product fields below the description and title field break? Do you need to deactivate Gutenberg just to keep your ecommerce business up and running?

What is Gutenberg?

Gutenberg is the new WordPress Editor. We wrote about it before at the beginning of this year actually. It will allow you to create content for posts, pages and custom post types just like WooCommerce Products using blocks. Here is a screenshot of what you see looking for blocks:

Gutenberg Blocks


And here one with some text added:

Text Block

Think of it as some of the Page Builders out there like Visual Composer, Beaver Builder or Divi. What is more, it will also make these options available in the customizer and perhaps frontend in the future as well.

Custom Fields and Gutenberg

As all is still under development it tends to be foggy sometimes and a lot of developers and end users are freaking out about it as it might break the way meta boxes / custom fields are used now. WooCommerce relies heavily on custom fields to add product data. And these fields may not work properly, or be moved to the new sidebar and so on. When you currently run the Gutenberg plugin to check you see it in action on a product page the WooCommerce custom fields are below it.

WooCommerce Custom Fields

But it is going to be way more integrated. Either they will be show below the block in a different way, go to the sidebar or they are going to come up with another solution.

Product Blocks

I am all for it and the sneak preview WooCommerce has shown looks very promising. And WooCommerce is working on product blocks already in their repo using a separate branch (code to be merged once done).

I installed the product blocks branch on my local WooCommerce Gutenberg Laravel Valet site and I can already see we can add a product block with ease inside a post:

Product Search Inside Woo Block

I just cannot search for my existing dummy products yet.  There seems to be a 404 issue

Here the no products found message:

Product Block Search

So I can’t go and add a product yet, but I can see we are closer than I thought and that is nice to see.

It is work in progress and perhaps my setup needs some REST API changes..? But the WooCommerce REST API is turned on though..

WooCommerce REST API


Well, that is something to try another time. Just like add products in x numbers and columns as Woo demoed. That I seem to not be able to do with this test branch yet.

The Future of WooCommerce with Gutenberg

I must say I am really exciting. I always found most page builder lacking a lot. Especially in the WooCommerce field. I want to be able to change the product page layout around. I want to be able to decide where the

  • product gallery,
  • description
  • cart button,
  • price and
  • other tabs with data


will be added. And I am positive that we will. Do see great options for the category or shop page in progress already. Rows and columns can be decided and hopefully thumbnail sizes in the future too. As for product page changes, well I expect to be able to move the mentioned elements around and WooCommerce did mention these as possibilities as well.

I expect to see way more in the upcoming weeks and months! Can’t say I am too worried. Big changes yes, but changes for the better to keep WordPress ahead of the game and compete with the likes of Shopify and Magento. And for WordPress to show others like Wix, Squarespace, Weebly and so on who’s boss. Exciting times!

Boost Sales with Algolia Search

Let’s face it, WordPress built-in search kind of blows. You can improve search and boost sales with Algolia Search. It will upgrade search to site wide search including products and offers suggestions! And it really easy to get going.

Improving WordPress Search

Visitors as we know can be an impatient bunch. So if we allow them to find what they need faster they are more likely to buy. Also, if search provides suggestions on what is available he or she might also go to a product though he was searching for blog content he saw earlier.

Unfortunately WordPress search out of the box sucks. Even a plugin like Better Search does not quite cut it. Sure it searches not just post, but other post types as well such as pages, but still it does not suggest other possible content, nor is it really fast.

Algolia Search to the rescue

Lighting fast search with search suggestions Google style  can now all be done with the power of Algolia Search. Algolia Search is used heavily in the Laravel community and at and with good reason.

Algolia Search

It is simply an amazing search integration. This is what is has on offer:

  • site-wide search
  • content suggestions while typing
  • suggests other options when the customer misspells something*

*Here example of misspelling where correct search term is suggested:

Misspelling and suggestions

And while you could integrate Google Search this is way prettier as in really integrates well. Just test it on our site. On typing suggestions popup in a dropdown from where a customer can click on a link. Each suggestion is also displayed with a small thumbnail based on the featured image.

Better Conversion and Lower Bounce Rate

All these features will prove that you can boost sales with Algolia Search. It will suggest possible products to buy and it will show these directly while searching. That is pretty amazing isn’t it. Besides a sales boost it is also just a general retention boost. It will lower your bounce rate as visitors will with ease be able to find follow up content, products and services to look at.


Let me just quote what they mentioned on the plugin description page here:

Algolia offers its Search as a Service provider on a incremental payment program, including a free Community Plan which includes 10,000 records & 100,000 indexing operations per month.
Beyond that, plans start at $35/month.

So you can stay on the free community plan post registration – needed for key – as long as you do not pass 10,000 records & 10,000 indexing operations per month. Indexing wise you should not have issues with that anytime soon on most sites and neither should you record wise.

We have had 2,452 records and 3,311 indexing operations so far with with 150+ post and close to 30 pages. Also during the trial the sky’s the limit really.


First of all you need to install their plugin. That is easy as always.

Search by Algolia – Instant & Relevant results

Next you will need to register to get your

  • application id,
  • search-only api key and
  • admin api key

and get your trial up and running. The plugin will guide you with this.

Algolia Settings


Then you need to choose the content you would like to be part of the searches and allow Algolia to index it under autocomplete and activate this. This will take some time as in will need to index and store it at Algolia for lightning fast future searches and suggestions.

Algolia Auto Complete

Search Page Choice

On Search page you can choose to use WordPress Search Page or the Algolia Search page:

Search Page and Algolia

This really depends on your preference. We are testing with at the moment.


Algolia Dashboard

Once you are setup you can keep track of indexing, searches done and much much more in their Dashboard.

Algolia Dashboard

I like the design and UI in general. It is easy to see what is going on. Do think I won’t be needing to check things here that much, but it is nice to have when search starts getting used a lot.

Rolling your Own

If you want to run it all for free and under your control you can clone the repo and roll your own on your own server. Just to to the repository at Github and get your own copy. Then install in on the same web server or a separate on, and integrate it with your site. Doing this all by yourself will require more technical knowhow and more server power of course, but you do keep all the data under your control

WooCommerce Cart in Theme Header

To add the WooCommerce Cart in the Theme Header and make it update based upon cart changes there are basically two steps to take. In this post I will go through them briefly.


This code is based on Isabel’s code, but slightly adjusted to deal with some WooCommerce changes and added notification:

PHP Notice: WC_Cart::get_cart_url is <strong>deprecated</strong> since version 2.5! Use wc_get_cart_url instead.
as well as some styling tweaks. So for a more detailed post do read her blog post on this. My thanks goes out to her for sharing the code as well as the styling!

Header Cart Loading

To load the WooCommerce Cart in Theme Header use this code below. The html tag you can of course change. I just added it so I could position the cart properly next to the menu in my Ianua theme. This is an updated snippet based of Isabel’s snippet as stated earlier. Only the wc_get_cart_url() has been added instead of the deprecated WC()->cart->get_cart_url().

<div class="woocommerce-cart">
<?php if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
$count = WC()->cart->cart_contents_count;
<a class="cart-contents"href="<?php echo wc_get_cart_url(); ?>"title="<?php_e( 'View your shopping cart' ); ?>">
if ( $count > 0 ) {
<span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
<?php } ?>

Cart Updates and Styling

The code snippet you need to add to your functions.php to update the cart count is still as is and indicated on her blog post so you can just copy it it off of her post. But here just in case the post is ever taken down:

 * Ensure cart contents update when products are added to the cart via AJAX
 * Created by Isabel
function my_header_add_to_cart_fragment( $fragments ) {
 $count = WC()->cart->cart_contents_count;
 ?><a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php
 if ( $count > 0 ) {
 <span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
 $fragments['a.cart-contents'] = ob_get_clean();
 return $fragments;
add_filter( 'woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment' );

The same goes for the styling. Though you may want to style things differently of course. Styling we used in the end was:

#nav-wrap .woocommerce-cart {
    float: right;
    padding: 15px 6px 15px 24px;
.cart-contents:before {
content: "\e01d";
color: white;
vertical-align: bottom;
.cart-contents:hover {
text-decoration: none;
.cart-contents-count {
color: #fff;
// background-color: #2ecc71;
font-weight: bold;
// border-radius: 10px;
padding: 1px3px;
line-height: 1;
font-family: Arial, Helvetica, sans-serif;
vertical-align: top;

So minimal changes really. Did not like the background and with a dark theme I needed things to be white for it to show well.