Okay
  Public Ticket #3690527
Expiration of roles assignment for users
Closed

Comments

  •  8
    Norbert started the conversation

    Hi there,

    Is there an option to have an assigned B2B role expire for a user? E.g. a user applies for a B2B role. We grant them this role but only for e.g. 1 year from today. After 1 year they are again automatically re-assigned the role of B2C user. The user would have to reapply for the B2B role.

    Thanks in advance,

    Maria

  •  2,167
    WebWizards replied

    Hi Maria,

    I'm afraid that we do not have any built-in option for this in the plugin.

    I think the easiest way you might achieve it, is maybe through a WP CRON JOB, that is registered using the hook 'woocommerce_created_customer'. It could be set so that after 1 year, it sets the user role to 'customer' and the B2BKing user group to B2C.


    In principle, I think a code snippet such as this one could work:

    add_action('woocommerce_created_customer', 'schedule_customer_role_change', 10, 1);
    function schedule_customer_role_change($customer_id) {
        // Schedule an event to run one year from the registration
        if (!wp_next_scheduled('change_customer_role_one_year', array($customer_id))) {
            wp_schedule_single_event(time() + YEAR_IN_SECONDS, 'change_customer_role_one_year', array($customer_id));
        }
    }
    // Add the custom action hook
    add_action('change_customer_role_one_year', 'change_customer_role_and_meta', 10, 1);
    function change_customer_role_and_meta($customer_id) {
        // Get the user object
        $user = new WP_User($customer_id);
        // Check if the user exists
        if ($user->exists()) {
            // Set the user role to 'customer'
            $user->set_role('customer');
            // Update user meta keys
            update_user_meta($customer_id, 'b2bking_b2buser', 'no');
            update_user_meta($customer_id, 'b2bking_customergroup', 'no');
        }
    }
    // Ensure cleanup of scheduled events if user is deleted
    add_action('delete_user', 'cleanup_scheduled_events');
    function cleanup_scheduled_events($user_id) {
        // Get all scheduled events for the user
        $timestamp = wp_next_scheduled('change_customer_role_one_year', array($user_id));
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'change_customer_role_one_year', array($user_id));
        }
    }
    

    Kind regards,

    Stefan