【问题标题】:Issue when trying get the product variation object from order items尝试从订单项中获取产品变体对象时出现问题
【发布时间】:2020-11-05 02:13:24
【问题描述】:

在 WooCommerce 上,我正在尝试获取产品的变体名称。 但我收到消息错误:调用未定义的函数 wc_get_product()。 这是代码:(此代码所在的文件来自向服务器发出请求的应用程序,因此它不在根目录中)。

$order_items = $order_data->line_items;
foreach ($order_items as $order_item) {
    if ($order_item->product_id == $product_id) {
        // Get variation if any
        $variation_id = $order_item->variation_id;
        $variation_name = wc_get_product($variation_id);
        $variation_name->get_formatted_name();

        if (empty($variation_id)) $variation_id = 0;

        $variation_prop = $product['variations'][$variation_id];
    }

}

感谢任何帮助。

编辑 2: $order_data 是这样得到的:

try {
                $woocommerce = new Client($f3->get('wprestbaseurl'), $f3->get('wprestconsumer_key'), $f3->get('wpconsumer_secret'), ['wp_api' => true, 'version' => 'wc/v3', 'query_string_auth' => (0 === strpos(strtolower($f3->get('wprestbaseurl')), 'https://'))]);
                // Retrieve given order meta data
                // System IDs are stored into the "xlspadlock_activations" custom field for each order.
                $order_data = $woocommerce->get("orders/$customer_order_id");
            }
catch{....

【问题讨论】:

  • 我完全理解@LoicTheAztec 这不是最好的帮助方式。但由于代码不是我的,我对发布有一些限制。但我恳请您的帮助!我将主帖编辑到 EDIT 2:,我在其中展示了 $order_data 是如何获得的。
  • 您似乎在外部文件上使用了一些 Rest API,WooCommerce 类和方法无法工作,如果您尝试使用它们会抛出错误。
  • 我不能直接从“wp-content\plugins\woocommerce\includes”调用它们,使用一些 url 路径?你看到替代品了吗? ;)
  • 我对 REST API 不够熟练,所以目前我对你没有任何线索。
  • 我知道这是一个具体的问题。感谢您的时间!我等着有人帮忙。

标签: php wordpress woocommerce orders product-variations


【解决方案1】:

更新 3

在更新和 cmets 之后,由于您似乎在外部文件上使用了一些 Rest API,WooCommerce 类和方法无法工作,如果您尝试使用它们会抛出错误。


初步答案:

自 WooCommerce 3 以来,您的代码存在一些错误,因为无法直接访问订单项目和产品属性。

改用WC_Order_Item_Product get product_id(), get_variation_id() and get_product() 方法如下:

$order_items = $order->get_items(); // Get order items

// Loop through order items
foreach ( $order_items as $item) {
    // Check for specific product Id and only for product variation items
    if ( in_array( $product_id, array($item->get product_id(), $item->get variation_id() ) ) && $item->get variation_id() > 0 ) {
        // Get product variation object
        $product_variation = $item->get_product();

        // Get the product variation formatted name
        $formatted_name   = $product_variation->get_formatted_name();
        
        // ...
    }
}

相关话题:

注意事项:在订单商品上,当商品为产品变体时,get product_id() 方法是父变量产品 ID,get_product() 方法给出产品变体实例对象。 p>

【讨论】:

  • 感谢 Loic,我编辑了我的主要帖子,添加了第一行代码。变体 ID 运行良好,但变体名称不是。我尝试了您的解决方案,但我不断收到此错误:[link] (ibb.co/99XB9fk)。基本上它适用于我使用的任何功能,我猜..
  • @TiagoSantos 需要定义 $order 对象以避免此错误......当您在外部文件上使用特殊 API 时,普通的 woocommerce 方式似乎不起作用......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 2021-02-04
  • 2021-10-10
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多