如何在 Woocommerce 中获取客户的最后订单

Arm*_*eri 3 php wordpress metadata orders woocommerce

我正在使用如何在 Woocommerce 中获取最新订单 ID答案代码,该代码通过自定义函数返回最后一个订单get_last_order_id()

这是我获取订单商品的代码尝试:

<?php

    $latest_order_id = get_last_order_id(); // Last order ID
    $order = wc_get_order( $latest_order_id ); // Get an instance of the WC_Order object
    $order_details = $order->get_data(); // Get the order data in an array
    $order_status = esc_html( wc_get_order_status_name( $order->get_status() ) );
    $order_items = $order_details['line_items'];
?>
Run Code Online (Sandbox Code Playgroud)

然后我在这段代码中使用它:

<div class="row last-order">
    <div class="col-md-7">
      <ul>
        <?php
        foreach ($order_items as $product_name) { ?>
          <li><?php echo $product_name['name']; ?></li>
        <?php
        }
        ?>
      </ul>
    </div>
    <div class="col-md-4 order-status-box">
      <h6 class="status"><?php echo $order_status; ?></h6>
      <i class="fas fa-chevron-down icon"></i>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我想获取当前客户的最后订单。如何更改自定义函数以获取当前客户的get_last_order_id()最后订单?

除了当前用户的最新订单之外,我还想接收购物车中的内容。

Loi*_*tec 13

更新:替换WC()->customernew WC_Customer( get_current_user_id() );以获得更好的兼容性。

ClassWC_Customer类包含get_last_order()获取客户最后订单的方法(因此您不再需要此答案线程get_last_order_id()中的自定义函数)

所以你的代码将是:

<?php

    // For logged in users only
    if ( is_user_logged_in() ) :

    $user_id = get_current_user_id(); // The current user ID

    // Get the WC_Customer instance Object for the current user
    $customer = new WC_Customer( $user_id );

    // Get the last WC_Order Object instance from current customer
    $last_order = $customer->get_last_order();

    $order_id     = $last_order->get_id(); // Get the order id
    $order_data   = $last_order->get_data(); // Get the order unprotected data in an array
    $order_status = $last_order->get_status(); // Get the order status
?>

<div class="row last-order">
    <div class="col-md-7">
        <ul>
        <?php foreach ( $last_order->get_items() as $item ) : ?>
            <li><?php echo $item->get_name(); ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
    <div class="col-md-4 order-status-box">
      <h6 class="status"><?php echo esc_html( wc_get_order_status_name( $order_status ) ); ?></h6>
      <i class="fas fa-chevron-down icon"></i>
    </div>
</div>

<?php endif; ?>
Run Code Online (Sandbox Code Playgroud)

经过测试并有效。

注意:现在,要“除了当前用户的最新订单外,还接收购物车的内容”,您将必须提出一个包含更多详细信息的新问题,请一次提出一个问题。

有关的: