在 WooCommerce 3 中更新产品库存数量和状态

Update product stock quantity and status in WooCommerce 3

当存在特定 post_meta

时,我正在尝试将产品的库存数量设置为零

我正在连接 'woocommerce_update_product'。当我单击“更新”时,它开始并正确更新;然而,行动永远不会结束。 (页面正在加载...)

当我刷新页面查看库存时,这个修改正确。

我做错了什么吗?

这是我的代码

add_action('woocommerce_update_product', 'sv_set_no_stock_when_discontinued', 10, 1);
function sv_set_no_stock_when_discontinued($prodId){

    $discontinued = get_post_meta($prodId, '_is_discontinued', true);

    if($discontinued == 'yes'){

        $product = wc_get_product($prodId);

        // Using WC setters
        $product->set_manage_stock(true);
        $product->set_stock_quantity(0);
        $product->set_stock_status('outofstock');

        // Save Product
        $product->save();
    }
}

放置一段时间后,出现以下错误:

Fatal error: Allowed memory size of 1077936128 bytes exhausted (tried to allocate 20480 bytes) in \wp-includes\meta.php on line 1078

Fatal error: Allowed memory size of 1077936128 bytes exhausted (tried to allocate 20480 bytes) in \wp-includes\class-wp-fatal-error-handler.php on line 72

WC_Product 对象已经包含在 woocommerce_update_product Hook 的第二个参数中……因此您可以稍微更改您的代码,例如:

但是 因为这个钩子位于 WC_Product_Data_Store_CPT Class, 它不太喜欢 WC_Product setter 方法,尤其是 save() 方法。

因此,我们将用以下内容替换此挂钩:

add_action( 'woocommerce_admin_process_product_object', 'set_no_stock_if_discontinued' );
function set_no_stock_if_discontinued( $product ) {
    if( $product->get_meta('_is_discontinued') === 'yes' 
    || ( isset($_POST['_is_discontinued']) 
    && esc_attr($_POST['_is_discontinued']) === 'yes' ) ) {

        // Using WC setters
        $product->set_manage_stock(true);
        $product->set_stock_quantity(0);
        $product->set_stock_status('outofstock');
    }
}

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。

Note: The save() method is not needed as it's triggered just after this hook.

Global note: You can also set "manage stock" to false.