skip to Main Content

I have a woocommerce cart icon in my main navigation. I want that icon to show a if the cart has items in it. If not that would be removed. I have tried the code below and it does not do what I intended it to. Ideas?

if($items_txt = $count_value === 1 ){
$html .= '<span class="xoo-wsc-sc-count">1</span>';}
elseif($items_txt = $count_value === 0 ){
$html .= '';}

Here is the full original code snippet.

<?php

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
    die;
}

$sy_options = get_option('xoo-wsc-sy-options');//Style options
$options    = get_option('xoo-wsc-gl-options');
$count_type = isset( $options['bk-count-type']) ? $options['bk-count-type'] : 'qty_count'; //Count Type
$cart_items_total = wc_price(WC()->cart->subtotal);

$bk_cubi    = isset( $sy_options['bk-cubi']) ? $sy_options['bk-cubi'] : ''; // Custom basket icon
if( !$bk_cubi ){
    $bk_bit = isset( $sy_options['bk-bit']) ? $sy_options['bk-bit'] : 'xoo-wsc-icon-basket1'; // Basket Icon Type
}


$html  = '<a class="xoo-wsc-sc-cont">';

if( $bk_cubi ){
    $html .= '<img src="'.$bk_cubi.'" class="xoo-wsc-sc-icon">';
}
else{
    $html .= '<span class="xoo-wsc-sc-icon '.$bk_bit.'"></span>';
}

if($count_type == 'qty_count'){
    $count_value = WC()->cart->get_cart_contents_count();
}
elseif($count_type == 'item_count'){
    $count_value = count(WC()->cart->get_cart());
}

$items_txt = $count_value === 1 ? __('item','side-cart-woocommerce') : __('items','side-cart-woocommerce');
$html .= '<span class="xoo-wsc-sc-count">'.'</span>';
//$html .= '<span class="xoo-wsc-sc-count">'.$count_value.'</span>';
//$html .= '<span class="xoo-wsc-sc-total">'.$cart_items_total.'</span>';



$html .= '</a>';

echo $html;

2

Answers


  1. I think if you change this if:

    if( $bk_cubi ){
        $html .= '<img src="'.$bk_cubi.'" class="xoo-wsc-sc-icon">';
    }
    else{
        $html .= '<span class="xoo-wsc-sc-icon '.$bk_bit.'"></span>';
    }
    

    To:

    if ($bk_cubi)
    {
        $html .= '<img src="'.$bk_cubi.'" class="xoo-wsc-sc-icon">';
    }
    else
    {
        if($count_value == 1 )
        {
            $html .= '<span class="xoo-wsc-sc-count">1</span>';
        }
    }
    

    You’ll get what you want.

    Also, a single = is assignment operator. == is for checking whether values are equal to one another.

    Login or Signup to reply.
  2. You can use the woocommerce_add_to_cart_fragments hook to check real-time woocommerce cart items.

    add_filter( 'woocommerce_add_to_cart_fragments', 'woo_cart_icon_count' );
    function woo_cart_icon_count( $fragments ) {
    
       $cart_count = WC()->cart->cart_contents_count;
       if($cart_count > 0) {
         // your code here
       }
    
    }
    

    For more detail, you can check the tutorial here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search