In WooCommerce possiamo visualizzare i contenuti del carrello come un oggetto JavaScript.
Aggiungiamo il seguente codice al file header.php del nostro tema.
<?php wp_head();?>
<script>
<?php
$js_items = array();
foreach ( WC()->cart->get_cart() as $cart_item ) {
$item_name = $cart_item['data']->get_title();
$quantity = $cart_item['quantity'];
$price = $cart_item['data']->get_price_html();
$img = wp_get_attachment_image_src( get_post_thumbnail_id( $cart_item['data']->get_id() ), 'thumbnail' );
$js_items[] = array(
'title' => $item_name,
'url' => get_permalink( $cart_item['data']->get_id() ),
'quantity' => $quantity,
'price' => $price,
'image' => $img[0]
);
}
?>
var myCart = {
itemsCount: <?php echo WC()->cart->get_cart_contents_count(); ?>,
total: <?php echo WC()->cart->total; ?>,
items: <?php if( count( $js_items ) > 0 ): echo json_encode( $js_items ); else: ?> []<?php endif; ?>
};
</script>
</head>
Ora l'oggetto myCart contiene i dati aggiornati del carrello che possiamo utilizzare nel nostro codice JavaScript.