【问题标题】:Get Product ID and Variation ID from an Order ID from outside wordpress从外部 wordpress 的订单 ID 中获取产品 ID 和变体 ID
【发布时间】:2018-11-21 08:22:44
【问题描述】:

我正在尝试 PHP/MYSQL 从 订单 ID

查询 WooCommerce 产品 ID/变体 ID
  • 如果订单中的产品是简单的,则获取产品 ID

  • 如果订单中的产品是可变的,则获取变体 ID

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

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

【问题讨论】:

    标签: php mysql wordpress woocommerce


    【解决方案1】:

    使用 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
    }
    

    注意文档,

    wc_get_order();

    WC_Order();

    WC_Order_Item();

    WC_Order_Item_Product();

    【讨论】:

    • 小心,我担心$item->get_type() 不会返回 variablesimpleline_item
    • 我希望我早点看到@PabloSGPacheco 的评论。 is_type 确实返回 'line_item' 并证明无济于事。最好只使用$product_id = $item->get_product_id()$product_variation_id = $item->get_variation_id()
    • @ericK 很高兴我的评论很有用。确切地说,如果我没记错的话,如果你在一个不是可变产品的项目中检查$item->get_variation_id(),你会得到零。也许这确实是一种更可靠的方法
    • 如果你想要简单的产品 id 和变体的变体 id,那么你可以使用这个:$pid = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();
    【解决方案2】:

    正如您在注释“我正在编写的脚本独立于 WordPress”中提到的那样。
    然后会有一个查询,您可以使用

    从产品 ID 获取变体 ID 列表。
    wp_posts 中选择 ID,其中 post_parent = "PRODUCT_ID" AND post_type LIKE 'product_variation'

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      相关资源
      最近更新 更多