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

如何获取WooCommerce购物车中各商品的发布者ID

获取WooCommerce购物车商品的作者ID

没问题!要获取购物车中每个商品的作者ID(也就是创建并发布该商品的用户ID),你可以直接利用WordPress的文章属性来实现——因为WooCommerce商品本质上是WordPress的自定义文章类型,每个商品都自带post_author字段,对应发布它的用户ID。

下面是在你现有代码基础上修改后的版本,我已经添加了获取作者ID及相关信息的代码:

foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ){ 
    $product_id = $cart_item['product_id']; // Product ID 
    $product_obj = wc_get_product($product_id); // Product Object 
    $product_qty = $cart_item['quantity']; // Product quantity 
    $product_price = $cart_item['data']->price; // Product price 
    $product_total_stock = $cart_item['data']->total_stock; // Product stock 
    $product_type = $cart_item['data']->product_type; // Product type 
    $product_name = $cart_item['data']->post->post_title; // Product Title (Name) 
    $product_slug = $cart_item['data']->post->post_name; // Product Slug 
    $product_description = $cart_item['data']->post->post_content; // Product description 
    $product_excerpt = $cart_item['data']->post->post_excerpt; // Product short description 
    $product_post_type = $cart_item['data']->post->post_type; // Product post type 
    $cart_line_total = $cart_item['line_total']; // Cart item line total 
    $cart_line_tax = $cart_item['line_tax']; // Cart item line tax total 
    $cart_line_subtotal = $cart_item['line_subtotal']; // Cart item line subtotal 
    $cart_line_subtotal_tax = $cart_item['line_subtotal_tax']; // Cart item line tax subtotal 

    // --- 新增:获取商品作者ID及相关信息 ---
    $product_author_id = $cart_item['data']->post->post_author; // 商品作者ID(发布该商品的用户ID)
    // 可选:获取作者的用户对象,方便获取更多信息(比如用户名、邮箱等)
    $product_author_obj = get_user_by('id', $product_author_id);
    $product_author_username = $product_author_obj->user_login; // 作者用户名
    $product_author_email = $product_author_obj->user_email; // 作者邮箱
    // --- 新增结束 ---

    // variable products 
    $variation_id = $cart_item['variation_id']; // Product Variation ID 
    if($variation_id != 0){ 
        $product_variation_obj = wc_get_product($variation_id); // Product variation Object 
        $variation_array = $cart_item['variation']; // variation attributes + values 
    } 
}

小说明:

  • $cart_item['data']->post对应的是该商品的WordPress原生WP_Post对象,其中post_author字段就是发布该商品的用户ID,直接调用即可。
  • 如果你需要更多作者相关信息,比如用户名、邮箱,可以用get_user_by()函数通过作者ID获取完整的用户对象,再提取你需要的字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:20:38