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

如何在WooCommerce「我的账户」订单列表隐藏含指定ID商品的订单

原代码问题原因
  • 逻辑判断反向:需求为「只要订单包含商品ID=5就隐藏整个订单」,但现有代码逻辑为「遍历订单内每个商品,只要商品ID不等于5就输出订单行」,会触发两个问题:
    1. 若订单同时包含ID=5和其他ID的商品,遍历到其他商品时仍会输出订单行,无法隐藏目标订单
    2. 若订单有多个非ID=5的商品,同一个订单会被重复输出多次
  • 缺少跳出逻辑:没有在检测到目标商品后跳过整个订单的输出流程。
模板修改的修复方案

替换为以下代码即可实现模板层面的隐藏:

<tbody>
     <?php
     foreach ( $customer_orders->orders as $customer_order ) {
         $order      = wc_get_order( $customer_order ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
         $item_count = $order->get_item_count() - $order->get_item_count_refunded();
         
         // 标记订单是否包含需要隐藏的商品
         $has_hidden_product = false;
         foreach( $order->get_items() as $item ) {
             if ( $item->get_product_id() === 5 ) {
                 $has_hidden_product = true;
                 break; // 检测到目标商品直接跳出循环,减少性能消耗
             }
         }
         // 仅当订单不包含隐藏商品时输出订单行
         if ( !$has_hidden_product ) :
         ?>
         <tr class="woocommerce-orders-table__row woocommerce-orders-table__row--status-<?php echo esc_attr( $order->get_status() ); ?> order">
         <!-- 原有模板的订单行代码保持不变 -->
         ...
         </tr>
         <?php endif;
     }
     ?>
</tbody>
无需覆写模板的Hook实现方案(推荐)

直接将以下代码添加到当前主题的functions.php文件或自定义功能插件中,即可通过过滤器修改订单查询逻辑,从根源排除包含目标商品的订单,不受模板更新影响:

add_filter( 'woocommerce_my_account_my_orders_query', 'custom_hide_orders_with_specific_product', 10, 1 );
function custom_hide_orders_with_specific_product( $args ) {
    // 可修改为需要隐藏的商品ID,多个ID请用数组格式如 [5,6,7]
    $hidden_product_id = 5;

    // 查询当前用户所有包含目标商品的订单ID
    $hidden_order_ids = wc_get_orders( [
        'limit'       => -1,
        'customer_id' => get_current_user_id(),
        'status'      => array_keys( wc_get_order_statuses() ),
        'return'      => 'ids',
        'meta_query'  => [
            [
                'key'     => '_product_id',
                'value'   => $hidden_product_id,
                'compare' => is_array($hidden_product_id) ? 'IN' : '=',
            ]
        ]
    ] );

    // 排除目标订单
    if ( !empty( $hidden_order_ids ) ) {
        $args['post__not_in'] = $hidden_order_ids;
    }

    return $args;
}

注:该方案优先级高于模板修改,无需额外调整模板代码即可生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:09:04