我需要添加一个功能,在购买特定产品(按ID或类别)后更改用户的角色。我怎么能这样做?
答案 0 :(得分:0)
您可以使用此代码
add_action( 'woocommerce_order_status_completed', 'misha_change_role_on_purchase' );
function misha_change_role_on_purchase( $order_id ) {
// get order object and items
$order = new WC_Order( $order_id );
$items = $order->get_items();
$product_id = 55; // that's a specific product ID
foreach ( $items as $item ) {
if( $product_id == $item['product_id'] && $order->user_id ) {
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'customer' );
// Add role
$user->add_role( 'subscriber' );
}
}
}
如果您想按类别进行检查,只需添加has_term( $category_id, 'product_cat', $item['product_id'] )