订单状态完成后更改产品类别
一旦 WooCommerce 中的订单状态完成",我想将新类别应用于产品.假设产品在(A 类)中,我想在订单状态已完成"上申请(B 类).
I want to apply new category to product once the order status get "completed" in WooCommerce. Let's say that the Product is in (category A) and I want to apply (category B) on order status "completed".
有没有办法做到这一点?
Is there any way to do this?
我找到了几个教程,但不知道如何组合它们:
I found couple of tutorials but don't know how to combine them:
https://wordpress.org/support/主题/自动添加帖子到一个类别的条件
我怎样才能做到这一点?
How can I achieve this?
谢谢!
更新
如果您想更改产品的 woocommerce 类别,您应该使用 wp_set_object_terms()
接受类别 ID 或 slug 带有 'product_cat'
分类参数 和 的本机 WordPress 函数不是 'category'
.
As you want to change the woocommerce category for a product, you should use
wp_set_object_terms()
native WordPress function that accept either the category ID or slug with'product_cat'
taxonomy parameter and NOT'category'
.
woocommerce_order_status_completed
钩子通常用于在订单更改为状态完成时触发回调函数.
The woocommerce_order_status_completed
hook is classically used to fire a callback function when order change to status completed.
这是代码:
add_action('woocommerce_order_status_completed', 'add_category_to_order_items_on_competed_status' 10, 1);
function add_category_to_order_items_on_competed_status( $order_id ) {
// set your category ID or slug
$your_category = 'my-category-slug'; // or $your_category = 123;
$order = wc_get_order( $order_id );
foreach ( $order->get_items() as $item_id => $product_item ) {
$product_id = $product_item->get_product_id();
wp_set_object_terms( $product_id, $your_category, 'product_cat' );
}
}
或者您也可以使用 woocommerce_order_status_changed
钩子和条件函数来过滤订单已完成"状态:
Or you can use also woocommerce_order_status_changed
hook with a conditional function that will filter order "completed" status:
add_action('woocommerce_order_status_changed', 'add_category_to_order_items_on_competed_status' 10, 1);
function add_category_to_order_items_on_competed_status( $order_id ) {
// set your category ID or slug
$your_category = 'my-category-slug'; // or $your_category = 123;
$order = wc_get_order( $order_id );
if ( $order->has_status( 'completed' ) ) {
foreach ( $order->get_items() as $item_id => $product_item ) {
$product_id = $product_item->get_product_id();
wp_set_object_terms( $product_id, $your_category, 'product_cat' );
}
}
}
此代码位于活动子主题或主题的 function.php 文件中.
此代码经过测试且功能齐全.