Get variations IDs from a variable product in Woocommerce 3

前端 未结 2 1457
死守一世寂寞
死守一世寂寞 2021-01-22 07:53

It is necessary to get the value from the array with the key [0], but the array is in the object. How can I put it in a variable?

  WC_Product_Variable Object          


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-22 08:41

    To get the children variation Ids for a variable product, use WC_product get_children() method (that doesn't have/allow any arguments):

    // (if needed) Get an instance of the WC_product object (from a dynamic product ID)
    $product = wc_get_product($product_id);
    
    // Get children product variation IDs in an array
    $children_ids = $product->get_children();
    
    // Get the first ID value
    $children_id = reset($children_ids); 
    // or 
    $children_id = $children_ids[0];
    

    Tested and works.

提交回复
热议问题