I am trying to create an order programmatically. Using wc_create_order()it is pretty simple:
$myProduct = new WC_Product(100);
$order = wc_create_order();
$order->add_product($myProduct, 1);
$order->calculate_totals();
This works as expected and an order is created for a simple product with ID 100 for the correct amount.
However, if I try to do this with a change, it does not seem to behave correctly. After much trial and error, I got this to sort the work this way:
$membershipProduct = new WC_Product_Variable(100);
$theMemberships = $membershipProduct->get_available_variations();
$trueProduct = new WC_Product(100);
$variationsArray = array();
foreach ($theMemberships as $membership) {
if ($membership['sku'] == $chosenVariation) {
$variationID = $membership['variation_id'];
$variationsArray = $membership['attributes'];
}
}
if ($variationID) {
$trueProduct->variation_id = $variationID;
}
$order = wc_create_order();
$order->add_product($trueProduct, 1, $variationsArray);
$order->calculate_totals();
However, although it creates an order with the correct product and the correct variation identifier, the amount for the order is always 0 (which, coincidentally, is the price of the first option).
$order->add_product() new WC_Product_Variable(), , , , . , WooCommerce , , .
-, , ?