在WooCommerce中以编程方式添加产品标签或术语,但请保留现有的标签

发布于 2025-01-31 03:54:44 字数 741 浏览 2 评论 0原文

我一直在阅读我想在WooCommerce上实现的此功能。这个想法是,一旦产品售罄,新的类别“售罄”将自动分配给它。

幸运的是,我遇到此答案代码。我添加了此代码:

function action_woocommerce_no_stock( $wc_get_product ) {
    $term_ids = array(769);
    $tag_ids = array(770);

    // Set category ids
    $wc_get_product->set_category_ids( $term_ids );

    // Product set tag ids
    $wc_get_product->set_tag_ids( $tag_ids );

    // Save
    $wc_get_product->save();
}
add_action( 'woocommerce_no_stock', 'action_woocommerce_no_stock', 10, 1 );

在我的functions.php中,它可以工作!问题在于它覆盖所有以前的类别。

如果有人可以指导我如何获取以前的“ product_cat”阵列,并将它们添加为“售罄”类别(769),我将非常感谢。

I've been reading about this functionality that I'd like to implement on my WooCommerce. The idea is that once a product is sold out, a new category "Sold Out" is automatically assigned to it.

Luckily, I've come across this answer code. I added this piece of code:

function action_woocommerce_no_stock( $wc_get_product ) {
    $term_ids = array(769);
    $tag_ids = array(770);

    // Set category ids
    $wc_get_product->set_category_ids( $term_ids );

    // Product set tag ids
    $wc_get_product->set_tag_ids( $tag_ids );

    // Save
    $wc_get_product->save();
}
add_action( 'woocommerce_no_stock', 'action_woocommerce_no_stock', 10, 1 );

To my functions.php and it works! the problem is that it overwrites all previous categories.

If anyone can guide me how to obtain the previous "product_cat" array and add them with the "Sold Out" category (769) I'd greatly appreciate it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╭ゆ眷念 2025-02-07 03:54:44

您可以首先使用get_category_ids()get_tag_ids(),然后 array_merge(),

因此您获得:

// Get product via product ID
$product = wc_get_product( 30 );

// Add this new term IDs
$term_ids = array( 15, 30 );

// Get existing category IDs
$category_ids = $product->get_category_ids();   

// Set category IDs
$product->set_category_ids( array_merge( $term_ids, $category_ids ) );

// Save
$product->save();

注意::在您的情况下

You can first use get_category_ids() OR get_tag_ids() and then array_merge()

So you get:

// Get product via product ID
$product = wc_get_product( 30 );

// Add this new term IDs
$term_ids = array( 15, 30 );

// Get existing category IDs
$category_ids = $product->get_category_ids();   

// Set category IDs
$product->set_category_ids( array_merge( $term_ids, $category_ids ) );

// Save
$product->save();

Note: in your case $wc_get_product is equal to $product

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文