Search code examples
woocommercehook-woocommerce

Display message based on cart items count in WooCommerce mini cart


I have added a static message inside WooCommerce mini cart with the following snippet, it appears right before the Checkout button:

add_action( 'woocommerce_widget_shopping_cart_total', 'my_custom_text', 15 );
function my_custom_text() {
  print '<p class="mini_cart_text">TEXT HERE</p>';  
}

I would like to make this text dynamic based on cart items count:

  • Cart items < 2 = text one
  • Cart items > 2 = text two

I tried to use this answer as a starting point by changing the initial part of the add_action with woocommerce_widget_shopping_cart_total that is where I want this text to appear.

I have used all the 3 examples gently provided but unfortunately nothing appears and I have no idea why.

Thanks


Solution

  • This will work:

    add_action( 'woocommerce_widget_shopping_cart_total', 'bbloomer_minicart_custom_text', 15 );
    
    function bbloomer_minicart_custom_text() {
        if ( ! WC()->cart ) return;
        if ( WC()->cart->get_cart_contents_count() > 2 ) {
            echo '<p class="mini_cart_text">TEXT TWO</p>';
        } else {
            echo '<p class="mini_cart_text">TEXT ONE</p>';
        }
    }
    

    *** Before testing the mini-cart again, please empty the Cart or update the quantity of one item in the Cart, so that the Cart cache is cleared.