Php 尝试从订单项获取产品变体对象时出现问题

Php 尝试从订单项获取产品变体对象时出现问题,php,wordpress,woocommerce,orders,product-variations,Php,Wordpress,Woocommerce,Orders,Product Variations,在WooCommerce上,我试图获得产品的变体名称。 但是我得到了错误消息:调用未定义的函数wc\u get\u product()。 代码如下:(代码所在的文件来自向服务器发出某些请求的应用程序,因此它不在根目录中) 感谢您的帮助 编辑2: $order_数据是通过以下方式获得的: try { $woocommerce = new Client($f3->get('wprestbaseurl'), $f3->get('wprestconsumer_

在WooCommerce上,我试图获得产品的变体名称。 但是我得到了错误消息:调用未定义的函数wc\u get\u product()。 代码如下:(代码所在的文件来自向服务器发出某些请求的应用程序,因此它不在根目录中)

感谢您的帮助

编辑2: $order_数据是通过以下方式获得的:

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{....

更新3


在更新和注释之后,由于您似乎正在外部文件上使用某些RESTAPI,WooCommerce类和方法无法工作,如果您尝试使用它们,将抛出错误


初始答案:

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

请使用以下方法:

$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\u id()
是父变量product id,方法
get\u product()
给出产品变体实例对象。

谢谢Loic,我编辑了我的主要帖子,添加了第一行代码。变体id工作正常,但变体名称不正常。我尝试了您的解决方案,但不断出现以下错误:[link]()。基本上,我想它适用于我使用的任何函数。@TiagoSantos$order对象需要定义以避免此错误…因为您在外部文件上使用特殊API,正常的方式似乎不起作用…我完全理解@LoicTheAztec,这并不是最好的帮助方式。但是由于代码不是我的,我对发布有一些限制。但我恳请你的帮助!我将主要帖子编辑为编辑2:,在这里我展示了$order_数据是如何获得的。由于您似乎在外部文件上使用了一些Rest API,WooCommerce类和方法无法工作,如果您尝试使用它们,它们将抛出错误。我不能使用一些url路径直接从“wp content\plugins\WooCommerce\includes”调用它们?你有别的选择吗?;)我对RESTAPI不够熟练,所以目前我没有任何线索可以告诉你。我知道这是一个具体的问题。谢谢你抽出时间!我等着有人来帮忙。
$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();
        
        // ...
    }
}