sinanisler logo

WooCommerce, Add User Role if User Buys Product

Let’s say you have a digital content or tutorial site and you only want to show the content to student role owning users.

You can sell your digital/ virtual product and ones the user buys and pays the product this codes will fire and add the student role automatically.

You just need to change the product ID 123 to your product to make this code work.

You can add the student role with this code if you need it.

/**
 * Function to automatically add the "Student" role to a user upon successful purchase of a specific product (ID 123).
 * This function hooks into the WooCommerce order completion process.
 * It checks each item in the completed order and, if the product with ID 123 is found, assigns the "Student" role to the user who made the purchase.
 */
function add_student_role_on_purchase($order_id) {
    $order = wc_get_order($order_id);
    $user = $order->get_user();
    if ($user) {
        // Loop through order items and check if product ID "123" is in the order
        foreach ($order->get_items() as $item) {
            if ($item->get_product_id() == 123) {
                // Add "Student" role to user
                $user->add_role('student');
                break;
            }
        }
    }
}

add_action('woocommerce_order_status_completed', 'add_student_role_on_purchase');

/**
 * Function to dynamically check if a logged-in user has purchased product ID "123" and does not have the "Student" role.
 * This function is hooked to the 'init' action, so it runs on every page load for logged-in users.
 * If a user has purchased the specified product but does not have the "Student" role, the role is added to their account.
 */
function check_and_add_student_role() {
    // Only run this check for logged-in users
    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();
        // Check if the current user does not have the "Student" role
        if (!in_array('student', $current_user->roles)) {
            // Check user's orders for product ID "123"
            $has_purchased = wc_customer_bought_product($current_user->user_email, $current_user->ID, 123);
            if ($has_purchased) {
                // Add "Student" role to user
                $current_user->add_role('student');
            }
        }
    }
}

add_action('init', 'check_and_add_student_role');




Leave the first comment