Skip to content
Advertisement

Create order details shortcode for WooCommerce

Hey I am trying to build a shortcode for my order details on the order received page.

The code below will generate the last result and then on top of it, it will display the word Array. My guess is that something in the foreach loop i am creating is still an array, but I dont know what to do next.

thanks for any help.

function getOrderItemList(){

  //set up array and Count
  $item_data = '';

  //get order ID
  global $wp;
  $order_id  = absint( $wp->query_vars['order-received'] );
  $order = wc_get_order( $order_id );
  $order_line_items = $order->get_items();

  //loop through each item in the order
  foreach ($order_line_items as $item) {

    $product = $item->get_product();
    $product_id = $item->get_product_id();
    $item_data = $item->get_data();

    $product_name = $item->get_name();
    $item_quantity  = $item->get_quantity();
    $item_total     = $order->get_formatted_line_subtotal( $item );
    $product_image = $product->get_image('order-received-item-image', $item);

    $item_data .= '<tr class="order-item-row"><td class="order-item-image">' . $product_image . '</td><td class="order-item-name"><p>' . $product_name . ' x ' . $item_quantity . '</p></td><td class="order-item-total"><p>' . $item_total . '</p></td></tr>';

  }

  $item_list = $item_data;

  $table .= <<<EOD
              <table class="test">
                $item_list
              </table>
              EOD;

  return $table;
}
    add_shortcode('order-line-item', 'getOrderItemList');

Advertisement

Answer

It looks like you jumbled a few things up, and had some unused variables in there. Try this.

function getOrderItemList() {
    // set up array.
    $item_list = '';

    // get order ID.
    global $wp;
    $order_id         = absint( $wp->query_vars['order-received'] );
    $order            = wc_get_order( $order_id );
    $order_line_items = $order->get_items();

    // loop through each item in the order.
    foreach ( $order_line_items as $item ) {

        $product       = $item->get_product();
        $product_name  = $item->get_name();
        $item_quantity = $item->get_quantity();
        $item_total    = $order->get_formatted_line_subtotal( $item );
        $product_image = $product->get_image( 'order-received-item-image', $item );

        $item_list .= '<tr class="order-item-row"><td class="order-item-image">' . $product_image . '</td><td class="order-item-name"><p>' . $product_name . ' x ' . $item_quantity . '</p></td><td class="order-item-total"><p>' . $item_total . '</p></td></tr>';

    }

    return "<table class="test">$item_list</table>";
}
add_shortcode( 'order-line-item', 'getOrderItemList' );
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement