WooCommerce 订单状态完成时根据产品 ID 和数量添加用户角色
我尝试根据几个不同的标准分配用户角色:
- 如果用户购买 Item-A,则分配 user-role-a。
- 如果用户购买了 Item-B,则分配 user-role-b。
- 如果用户购买了 2 个或更多 Item-B,则还会分配 user-role-c。
因此可以分配多个用户角色。基于购买产品后更改用户角色,这是我的尝试:
add_action( 'woocommerce_order_status_completed', 'wpglorify_change_role_on_purchase' );
function wpglorify_change_role_on_purchase( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
// CHILD PRODUCT MAKES PRIMARY ADULT ROLE
$product_id = 50; // that's the child product ID
foreach ( $items as $item ) {
if( $product_id == $item['product_id'] && $order->user_id ) {
$user = new WP_User( $order->user_id );
// Add new role
$user->add_role( 'primary-adult' );
}
}
// ADULT PRODUCT MAKES ADULT ROLE
$product_id = 43; // that's the adult product ID
foreach ( $items as $item ) {
if( $product_id == $item['product_id'] && $order->user_id ) {
$user = new WP_User( $order->user_id );
// Add new role
$user->add_role( 'adult' );
}
}
}
通过我的代码,我可以获得一些解决方案(根据购买的产品 ID 分配角色),但我仍然需要能够根据购买的商品的数量分配角色。有什么建议吗?
I'm trying to assign user roles based on a few different criteria:
- If a user purchases Item-A, user-role-a is assigned.
- If a user purchases Item-B, user-role-b is assigned.
- If a user purchases 2 or more of Item-B, user-role-c is also assigned.
So multiple user roles can be assigned. Based on Change User Role After Purchasing Product, this is my attempt:
add_action( 'woocommerce_order_status_completed', 'wpglorify_change_role_on_purchase' );
function wpglorify_change_role_on_purchase( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
// CHILD PRODUCT MAKES PRIMARY ADULT ROLE
$product_id = 50; // that's the child product ID
foreach ( $items as $item ) {
if( $product_id == $item['product_id'] && $order->user_id ) {
$user = new WP_User( $order->user_id );
// Add new role
$user->add_role( 'primary-adult' );
}
}
// ADULT PRODUCT MAKES ADULT ROLE
$product_id = 43; // that's the adult product ID
foreach ( $items as $item ) {
if( $product_id == $item['product_id'] && $order->user_id ) {
$user = new WP_User( $order->user_id );
// Add new role
$user->add_role( 'adult' );
}
}
}
With my code I was able to get a bit of a solution (assign roles based on purchased product IDs), but I still need to be able to assign a role based on the quantity of a purchased item. Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了回答你的问题之外,我还对你的代码进行了一些修改和优化:
$item->get_quantity()< /code> 可用于了解数量
因此您得到:
In addition to answering your question, I also modified and optimized your code a bit:
$item->get_quantity()
can be used to know the quantitySo you get: