【问题标题】:Check if the order item related product still exists in WooCommerce检查 WooCommerce 中是否仍然存在与订单项目相关的产品
【发布时间】:2019-04-29 15:34:41
【问题描述】:

我正在使用以下代码来显示一系列 WooCommerce 订单的数量和产品名称:

foreach ($order->get_items() as $item_id => $item_data) {

    // Get an instance of corresponding the WC_Product object
    $product = $item_data->get_product();

    $product_name = $product->get_name(); // Get the product name
    $item_quantity = $item_data->get_quantity(); // Get the item quantity
    echo $item_data->get_quantity() . ' x ' . $product->get_name() . ' (' . $product->get_sku() . ')<br />' ;
}

一切正常,但它卡在产品已被删除的特定订单上(因此产品 ID 不再存在)。

有什么方法可以检查这种情况并显示“产品不再存在”之类的内容并继续下一个产品?

【问题讨论】:

    标签: php wordpress woocommerce product orders


    【解决方案1】:

    以下将检查产品是否仍然存在以获取其 SKU(同时处理产品变体)

    // Loop through order items
    foreach ($order->get_items() as $item_id => $item ) {
        $product_id   = (int) $item->get_product_id(); // The product ID
        $variation_id = (int) $item->get_variation_id(); // The variation ID
        $item_name    = $item->get_name(); // Get the product name
        $item_qty     = $item->get_quantity(); // Get the item quantity
    
        // Get the product SKU: Check that the product exist
        if ( ( get_post_type( $product_id ) === 'product' && $variation_id === 0 )
        || ( get_post_type( $product_id ) === 'product' && $variation_id > 0 
        && get_post_type( $variation_id ) === 'product_variation' ) ) {
            // Get the WC_Product Object instance
            $product = $item->get_product();
    
            // Check if it is a valid WC_Product Object instance (and that the sku exist)
            if ( is_a($product, 'WC_Product') && $product->get_sku() != '' ) {
                $sku = ' ('.$product->get_sku().')'; // Get the sku
            } else {
                $sku = ''; // empty
            }
        } else {
            $sku = ''; // empty
        }
    
        // Output   
        echo $item_qty . ' &times; ' . $item_name . $sku . '<br>';
    }
    

    经过测试并且有效。

    注意:使用订单商品,您可以从订单商品中获取相关产品名称,而不是(因为它保存在订单商品本身上)

    【讨论】:

      猜你喜欢
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      相关资源
      最近更新 更多