php - WooCommerce:使用可变产品以编程方式创建订单

标签 php wordpress woocommerce

我正在尝试以编程方式创建订单。使用 wc_create_order() 这非常简单:

$myProduct = new WC_Product(100);
$order = wc_create_order();
$order->add_product($myProduct, 1);
$order->calculate_totals();

这按预期工作,并为 ID 为 100 的简单产品创建了正确数量的订单。

但是,如果我尝试使用变体来执行此操作,它的行为似乎并不正确。经过多次试验和错误后,我有点以这种方式工作:

$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();

但是,尽管它确实创建了包含正确产品和正确变体 ID 的订单,但订单总价始终为 0(巧合的是,这是第一个变体的价格)。

最初我尝试使用从 new WC_Product_Variable() 创建的对象来尝试 $order->add_product(),但这导致没有产品被添加到订单中所有,这让我相信这是一个问题,以编程方式使用可变产品创建订单。但是,按照这些调用的 WooCommerce 源代码,我看不出我做错了什么。

我是否遗漏了什么,或者有更好的方法来创建包含可变产品的订单?

最佳答案

解决了。

即使我可以发誓我已经尝试过(但失败了)这样做,答案是不添加 parent 产品($trueProduct 在示例),但要通过 ID 添加变体产品。

这之前可能失败了,因为,如@helgatheviking请注意,根据 source,我的 $variationsArray 格式不正确;我需要一个带有 ['variation'] 键的数组来发送正确的属性变体数组。

总的来说,我的工作代码现在看起来像这样:

$membershipProduct = new WC_Product_Variable(100);
$theMemberships = $membershipProduct->get_available_variations();

$variationsArray = array();

foreach ($theMemberships as $membership) {
    if ($membership['sku'] == $chosenVariation) {
        $variationID = $membership['variation_id'];
        $variationsArray['variation'] = $membership['attributes'];
    }
}

if ($variationID) {
    $varProduct = new WC_Product_Variation($variationID);

    $order = wc_create_order();
    $order->add_product($varProduct, 1, $variationsArray);
    $order->calculate_totals();
}

关于php - WooCommerce:使用可变产品以编程方式创建订单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32542793/

相关文章:

php - 当数量大于1时如何循环?

php - 将列更新为组中的最小值

css - Wordpress:CSS 在子页面内保持菜单项处于事件状态

javascript - Masonry/Isotope.js 无法正常工作

php - 在 Woocommerce 的单个产品页面中添加产品备注字段

php xpath 获取带有类的div 的内容

php - 为什么 GROUP_CONCAT + DISTINCT 在某些服务器上会触发内存不足(需要 8388580 字节)?

wordpress - 将 woocommerce 产品连接到帖子

php - 当标题已经在以前的文件中发送时,如何更改标题以在 WordPress 中下载文件?

php - Woocommerce - 允许针对不同状态再次订购