You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复WooCommerce展示用户最后订单时无订单用户的致命错误

存在的问题

1. 无订单用户的致命错误

当登录用户没有任何历史订单时,$customer->get_last_order() 会返回null,你没有做非空校验就直接调用$last_order的对象方法,直接触发致命错误。

2. 模板代码语法与逻辑错误

  • 拼接商品缩略图的代码中,</div> 外侧漏写单引号,存在PHP语法错误
  • $item_name 变量未提前定义就直接拼接使用,会抛出未定义变量警告
  • 缺少对订单商品是否存在的校验,如果订单对应的商品已被后台删除,$item->get_product()会返回null,调用get_image()时也会报错

修复后的完整代码

第一步:修复后台钩子逻辑

add_action( 'woocommerce_account_dashboard', 'recent_order', 1 );
function recent_order(){
    // 仅对登录用户生效
    if ( ! is_user_logged_in() ) {
        return;
    }

    $user_id = get_current_user_id();
    $customer = new WC_Customer( $user_id );
    $last_order = $customer->get_last_order();

    // 新增非空判断,无订单直接返回不渲染内容
    if ( empty( $last_order ) ) {
        return;
    }

    // 有订单才读取订单信息
    $order_id     = $last_order->get_id();
    $order_data   = $last_order->get_data();
    $order_status = $last_order->get_status();
    $date_created  = $last_order->get_date_created();
    $order_total = $last_order->get_total();
?>

第二步:修复前端模板逻辑

<div class="row last-order">
  <h3>Derniere commande</h3>
<div>
    <div>
  <h6>État : <?php echo esc_html( wc_get_order_status_name( $order_status ) ); ?></h6>
    <p>COMMANDE N° <?php echo $order_id;?></p>
</div>
    <p><?php echo $order_total."€"; ?></p>
    <p>
        <?php 
            setlocale(LC_TIME, 'fr_FR');
            date_default_timezone_set('Europe/Paris');
            echo utf8_encode(strftime('%d %B %Y', strtotime($date_created)));
        ?>
    </p>
    <div>
    <?php foreach ( $last_order->get_items() as $item ) : ?>
        <?php 
            $product   = $item->get_product();
            $item_name = ''; // 提前初始化变量
            // 新增商品存在性判断
            if ( ! empty( $product ) ) {
                $thumbnail = $product->get_image(array( 50, 50));
                if( $product->get_image_id() > 0 ){
                    // 补全语法错误的单引号
                    $item_name = '<div class="item-thumbnail">' . $thumbnail . '</div>';
                }
            }
            echo $item_name . $item->get_name();
        ?>
    <?php endforeach;?>
    </div>
    <div>
        <p>Tout Voir></p>
    </div>
</div>
<?php
}
?>

内容的提问来源于stack exchange,提问作者Loris GFT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:39:04