本文介绍了当产品保存在 WooCommerce 后端时,以编程方式为库存状态分配标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了 3 个标签 1.

I have created 3 tags 1.

  • 延期交货(ID 111)
  • 有货(ID 112),
  • 缺货 (id 113)

我希望根据可用性自动分配这些标签.

I would like these tags to be auto-assigned based on availability.

如果我能做到这一点,我将使用 woocommerce_admin_process_product_objectwoocommerce_product_quick_edit_savewoocommerce_product_set_stockwoocommerce_variation_set_stock 来捕捉库存状态变化的可能场景.

If I am able to get this working, I'll be using the woocommerce_admin_process_product_object, woocommerce_product_quick_edit_save, woocommerce_product_set_stock, woocommerce_variation_set_stock to capture the possible scenarios for stock status changes.

下面是我尝试过的,但它给了我一个致命的错误.如果我不使用 if 条件,那么标签会被分配,但它不符合我的目标.有什么建议吗?

Below is what I have tried but it gives me a fatal error. If I do not use the if condition, then the tags get assigned but it does not meet my objective. Any advice?

add_action( 'woocommerce_admin_process_product_object', 'mycode_woocommerce_backorder_tag', 10, 2 );
function mycode_woocommerce_backorder_tag ($wc_get_product, $product) {
    if ($product->managing_stock() && $product->is_on_backorder(1)) {
        $wc_get_product->set_tag_ids(array(111));
        $wc_get_product->save();
        //wp_set_object_terms ($post_id, 'onbackorder', 'product_tag');
    }
}

推荐答案

woocommerce_admin_process_product_object 钩子只有 1 个参数,即 $product

woocommerce_admin_process_product_object hook has only 1 argument, which is $product

$product->save(); 也不是必需的,因为这会自动发生

$product->save(); is also not necessary, because this happens automatically

复制自 admin/meta-boxes/class-wc-meta-box-product-data.php

Copied from admin/meta-boxes/class-wc-meta-box-product-data.php

/**
 * Set props before save.
 *
 * @since 3.0.0
 */
do_action( 'woocommerce_admin_process_product_object', $product );

$product->save();


所以要回答你的问题,你会得到:


So to answer your question, you get:

// When product is saved in WooCommerce backend
function action_woocommerce_admin_process_product_object( $product ) {
    // managing_stock() - returns whether or not the product is stock managed.
    // on_backorder() – check if a product is on backorder.
    if ( $product->managing_stock() && $product->is_on_backorder(1) ) {
        // Product set tag ids
        $product->set_tag_ids( array( 111 ) );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );

这篇关于当产品保存在 WooCommerce 后端时,以编程方式为库存状态分配标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:53