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