【问题标题】:WooCommerce Product Stock Quantities for Multiple Items多个项目的 WooCommerce 产品库存数量
【发布时间】:2017-04-17 06:26:06
【问题描述】:

在 WooCommerce 中,我基本上需要为 4 种单独的产品设置 10 的库存数量,因此当有人购买其中 1 种产品时,整体库存水平会下降到 9。

这些产品的库存数量必须关联,因此当购买 1 件时,所有这些产品的数量都会下降。

我不能简单地将 1 个产品设置为“可变产品”来实现这一目标,因为每个产品都必须是“简单产品”。

有谁知道设置 WooCommerce 的插件或方法来实现这一点?

【问题讨论】:

  • 你想什么时候触发这个事件?仅在订单完成时?

标签: php wordpress woocommerce product orders


【解决方案1】:

您可以尝试使用 woocommerce_thankyou 挂钩的自定义函数,首先获取客户订单中已购买产品的最小库存值,然后使用此库存值更新所有产品.这是未经测试的,所以你必须给我一些反馈。

代码如下:

add_action( 'woocommerce_thankyou', 'updating_product_unified_stock', 10, 1 );
function unifying_product_stock($order_id){

    $stock_updated = get_post_meta($order_id, 'stock_updated', true);

    if(empty($stock_updated)):

        // Inserting in the order meta data a custom field value to avoid repetition of this code, 
        // if the customer reload the "Order received" page…
        update_post_meta($order_id, 'stock_updated', 'yes');

        $products_stock_arr = array();
        $products_ids = array();

        // Getting the Order Object post data
        $order = wc_get_order( $order_id );

        foreach ( $order->get_items() as $item_id => $item ) {
            $product_stock = get_post_meta($item_id, '_stock', true);
            $products_stock_arr[] = $product_stock; // adding the product stock in the array
        }

        // Get the smallest stock value in the array of stock values
        $new_stock_number = min($products_stock_arr);

        // get all published simple products
        $all_products = get_posts( array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'post_status' => 'publish'
        )); 

        // Iterating through each published product
        // UPDATING PRODUCTS WITH THE NEW STOCK VALUE: 
        foreach( $all_products as $product)
            update_post_meta( $product_id, '_stock', $new_stock_number );
    endif;  
}

此代码位于您的活动子主题(或主题)的 function.php 文件中或任何插件 php 文件中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2018-05-25
    • 2016-05-06
    • 2023-04-02
    • 2019-07-10
    相关资源
    最近更新 更多