1
votes

I am trying to display the total number of items in the cart on various locations

1) Cart Page 2) Checkout Page 3) Email order receipt to client 4) Email order receipt to admin

I am using the following function to calc the total nos of items in the cart

 // function to calc total number items in basket
 function gh_custom_checkout_field( $checkout ) {        
 return WC()->cart->get_cart_contents_count();
 } 

Does anyone know how I can display the value on the locations above?

I have tried using my_custom_checkout_field() ?> but this just gave an internal server error.

1
lol sorry was a mistakeJames Donald

1 Answers

1
votes

1) For cart and checkout

You can use your function (without $checkout variable as it's not needed) as a shortcode:

function get_cart_count() {        
    return WC()->cart->get_cart_contents_count();
}
add_shortcode( 'cart_count', 'get_cart_count');

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

You will use it:

  • In the WordPress text editor: [cart_count]
  • In php code: echo do_shortcode( "[cart_count] ");
  • In mixed php/html code: <?php echo do_shortcode( "[cart_count] "); ?>

2) For Orders and email notifications

As the corresponding cart object doesn't exist anymore, you need to get the order items count from the WC_Order object (or the Order ID if you dont have it).

You can use this custom function, with a mandatory defined argument that can be the WC_Order object or the Order ID. If not the function will return nothing:

function get_order_items_count( $mixed ) {        
    if( is_object( $mixed ) ){
        // It's the WC_Order object
        $order = $order_mixed;
    } elseif ( ! is_object( $mixed ) && is_numeric( $mixed ) ) {
        // It's the order ID
        $order = wc_get_order( $mixed ); // We get an instance of the WC_order object
    } else {
        // It's not defined as an order ID or an order object: we exit
        return;
    }
    $count = 0
    foreach( $order->get_items() as $item ){
        // Count items
        $count += (int) $item->get_quantity()
    }
    return $count;
}

You will use it always setting as argument for the function an existing dynamic variable $order_id or $order like

echo get_order_items_count( $order_id ); // Dynamic Order ID variable

Or

echo get_order_items_count( $order ); // Dynamic Order object variable