Question: Woocommerce - Can't display image within loop of cart items


Woocommerce - Can't display image within loop of cart items

Answers 1
Added at 2017-11-30 18:11

I have a loop of cart items in Woocommerce that currently only displays the name, quantity and price. I'm trying to also get the image thumbnail to display but it either gives me an error and the page doesn't load at all or it does load but it doesn't show anything.

                global $woocommerce;
                $items = $woocommerce->cart->get_cart();
                $currency = get_woocommerce_currency_symbol();
                if (!$items) {
                    echo '<span class="no-items-mini">No items added</span>';
                    foreach($items as $item => $values) { 
                        $_product = $values['data']->post; 
                        $link = get_permalink($_product);
                        echo "<span>";
                            echo $values['quantity']." x <a href='".$link."'>".$_product->post_title;
                        echo "<a/></span>";
                        $price = get_post_meta($values['product_id'] , '_price', true);
                        echo "  Price: ".$currency.$price."<br>";
                        $image = wp_get_attachment_image_src( $values['product_id'], 'single-post-thumbnail' );
                        echo "<img src=$image[0];/>";
                $total = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) );
                echo "<span class='mini-total'><b>Total: </b>".$currency.$total."</span>";
Answers to

Woocommerce - Can&#39;t display image within loop of cart items

nr: #1 dodano: 2017-11-30 19:11

I have revisited your code, please try it:


    if ( WC()->cart->is_empty() ) {
        echo '<span class="no-items-mini">No items added</span>';
    } else {
        $currency = get_woocommerce_currency_symbol();
        $cart_total = WC()->cart->cart_contents_total;
        foreach(WC()->cart->get_cart() as $cart_item ) {
            $_product = $cart_item['data'];
            $link = $_product->get_permalink();
            echo '<span>';
            echo $cart_item['quantity'].' x <a href="'.$link.'">'.$_product->get_title();
            echo '<a/></span>';
            $price = $_product->get_price();
            echo "  Price: " . $currency . $price . "<br>";
            echo $_product->get_image();
    echo "<span class='mini-total'><b>Total: </b>". $currency . $cart_total ."</span>";


Its should work this time.

Source Show
◀ Wstecz