【问题标题】:How to get the last order of a customer in Woocommerce如何在 Woocommerce 中获取客户的最后一个订单
【发布时间】:2019-12-27 10:01:31
【问题描述】:

我正在使用 "How can I get the latest order id in Woocommerce" 答案代码,它通过自定义函数 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'];
?>

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

<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>

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

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

【问题讨论】:

  • 在 WHERE 子句中包含 post_author 的条件 then ...?
  • 谢谢现在更好@LoicTheAztec

标签: php wordpress woocommerce metadata orders


【解决方案1】:

更新:将WC()-&gt;customer 替换为new WC_Customer( get_current_user_id() ); 以获得更好的兼容性。

WC_Customer 类包含 get_last_order() 方法来获取客户的最后一个订单(因此您不再需要来自 this answer thread 的自定义函数 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; ?>

经过测试并且有效。

注意:现在要“接收购物车中的内容以及当前用户的最新订单”,您将需要提出一个新问题详细信息,请当时一个问题。

相关:

【讨论】:

  • @PullataPraveen 此代码在上一个 WooCommerce 版本上仍然可以完美运行。您的评论完全不清楚……您在说什么模板?你是如何嵌入代码的。你最好问一个新问题来解释事情!
  • 如果客户是客人怎么办?
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多