I'm trying to create an order programmatically. Using wc_create_order()
this is pretty straightforward:
$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 variation, it doesn't seem to behave correctly. After much trial and error, I got it to sort-of 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 does create the order with the correct product and the correct variation ID, the total for the order is always 0 (which, coincidentally, is the price of the first variation).
Originally I was trying $order->add_product()
with the object created from new WC_Product_Variable()
, but that resulted in no products being added to the order at all, which leads me to believe it's an issue with creating orders programmatically with variable products. However, following the WooCommerce source code for these calls, I can't see what I'm doing wrong.
Is there something I'm missing, or a better way to create an order with a variable product?
add_product( $product, $qty = 1, $args = array() )
. You need to pass$args = array('variation' => $something );
. I am not yet sure how that$something
needs to be formatted. – helgatheviking'variation'
key. I've added that ($variationsArray['variation'] = $membership['attributes'];
) and now the item appears 'correctly' in the order (as in, it's the right variation of the right product), but the price is still wrong. No idea what I'm missing! – indextwo