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

如何在WooCommerce后台订单列表自定义列显示每个订单项的库存数量

WooCommerce 后台订单列表自定义列显示产品剩余库存解决方案

你原有代码缺少获取产品库存的逻辑,直接替换为以下修改后的代码即可实现你要的Product A × 1 (3)格式效果:

add_filter('manage_edit-shop_order_columns', 'new_order_items_column' );
function new_order_items_column( $order_columns ) {
    $order_columns['order_products'] = "Productos";
    return $order_columns;
}

add_action( 'manage_shop_order_posts_custom_column' , 'new_order_items_column_cnt' );
function new_order_items_column_cnt( $colname ) {
    global $the_order; // 全局订单对象

    if( $colname == 'order_products' ) {
        // 获取订单所有商品项
        $order_items = $the_order->get_items();

        if ( !is_wp_error( $order_items ) ) {
            foreach( $order_items as $order_item ) {
                // 获取对应产品对象
                $product = $order_item->get_product();
                $stock_html = '';
                // 判断产品存在且启用了库存管理
                if( $product && $product->managing_stock() ) {
                    $stock_qty = $product->get_stock_quantity();
                    $stock_html = ' (' . $stock_qty . ')';
                }
                // 输出格式:产品名 × 数量 (库存)
                echo '▪️ ' . $order_item['name'] .' × <a href="' . admin_url('post.php?post=' . $order_item['product_id'] . '&action=edit' ) . '">'. $order_item['quantity'] .'</a>'. $stock_html .'<br />';
            }
        }
    }
}

核心修改说明

  • 调用$order_item->get_product()获取订单项对应的产品实例,自动兼容普通产品、可变产品的变体库存读取
  • 增加库存启用判断,仅当产品开启了库存管理时才显示库存值,避免无库存产品输出空括号
  • 库存值拼接在数量链接的后方,完全匹配你需要的展示格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 21:06:04