从外部 wordpress 的订单 ID 中获取产品 ID 和变体 ID

Kar*_*nor 3 php mysql wordpress woocommerce

我正在尝试从订单 ID 中PHP/MYSQL 查询 WooCommerce产品 ID/变体ID

  • 如果订单中的产品很简单,请获取产品 ID

  • 如果订单中的产品是可变的,则获取 Variation ID(s)

  • 如果(简单和可变)都得到(产品 ID(s)和变体 ID(s))

注意:我编写的脚本独立于 WordPress。

Chr*_*ris 9

使用 WooCommerce API 的各个方面,这可以使用以下某些版本来完成。

$order_id = XXX;

$order = wc_get_order( $order_id ); //returns WC_Order if valid order 
$items = $order->get_items();   //returns an array of WC_Order_item or a child class (i.e. WC_Order_Item_Product)

foreach( $items as $item ) {

    //returns the type (i.e. variable or simple)
    $type = $item->get_type();

    //the product id, always, no matter what type of product
    $product_id = $item->get_product_id();

    //a default
    $variation_id = false;

    //check if this is a variation using is_type
    if( $item->is_type('variable') ) {
        $variation_id = $item->get_variation_id();
    }

    //more code
}
Run Code Online (Sandbox Code Playgroud)

注意文档,

wc_get_order();

WC_Order();

WC_Order_Item();

WC_Order_Item_Product();

  • 小心,恐怕 `$item->get_type()` 不会返回 **variable** 或 **simple** 但 **line_item** (5认同)