简体   繁体   中英

Cart item title isn't concatenated into an HTML table in WooCommerce

I have create a Short-Code to list all the item name as follow,

add_shortcode( 'show_cart_items', 'tcf_show_cart_items' );
function tcf_show_cart_items()
{
    $cart   =   '<table>';
                foreach(  WC()->cart->get_cart() as $cart_item )
                {
                    $cart .= '<tr>' . $cart_item['data']->get_title() . '</tr>';
                }
    $cart   .=  '</table>';

    return $cart;
}

this is working fine but what I am facing is the items printing out of the table. You can see the output as screenshot when I inspecting on the web page and item name which was not printing in side the HTML table is highlighted in yellow.

在此处输入图片说明

My questions are,

  1. What is the reason for this?
  2. How to fix this?

TIA.

try below code, may be concatenate skip code

add_shortcode( 'show_cart_items', 'tcf_show_cart_items' );
function tcf_show_cart_items()
{
    $cart_item = '';

    foreach(  WC()->cart->get_cart() as $cart_item )
    {
        $cart_item .= '<tr>' . $cart_item['data']->get_title() . '</tr>';
    }

    $cart   =   '<table>'.$cart_item.'</table>';

    return $cart;
}

You have just forget to add <td> html tag around the title this way:

add_shortcode( 'show_cart_items', 'tcf_show_cart_items' );
function tcf_show_cart_items()
{
    $cart   =   '<table>';
                foreach(  WC()->cart->get_cart() as $cart_item )
                    $cart .= '<tr><td>' . $cart_item['data']->get_title() . '</td></tr>';
    $cart   .=  '</table>';

    return $cart;
}

Or also this way:

add_shortcode( 'show_cart_items', 'tcf_show_cart_items' );
function tcf_show_cart_items()
{
    $cart   =   '<table><tr>';
                foreach(  WC()->cart->get_cart() as $cart_item )
                    $cart .= '<td>' . $cart_item['data']->get_title() . '</td>';
    $cart   .=  '</tr></table>';

    return $cart;
}

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

Tested and works now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM