members_delete_role

The members members delete role function.

Published Date - July 31, 2023

Description

Function for safely deleting a role and transferring the deleted role's users to the default role. Note that this function can be extremely intensive. Whenever a role is deleted, it's best for the site admin to assign the user's of the role to a different role beforehand.

members_delete_role( $role );

Parameters

  1. $role


Usage

The following example is for adding a hook callback.

if ( !function_exists( 'members_delete_role' ) ) {
    require_once ABSPATH . PLUGINDIR . 'membersmembers/admin/functions-admin.php';
}

// The input(s). 
$role = null;

// NOTICE! Understand what this does before running.
$result = members_delete_role( $role );
            

Defined

The function is defined in the following location(s).

members/admin/functions-admin.php

function members_delete_role( $role ) {

	// Get the default role.
	$default_role = get_option( 'default_role' );

	// Don't delete the default role. Site admins should change the default before attempting to delete the role.
	if ( $role == $default_role )
		return;

	// Get all users with the role to be deleted.
	$users = get_users( array( 'role' => $role ) );

	// Check if there are any users with the role we're deleting.
	if ( is_array( $users ) ) {

		// If users are found, loop through them.
		foreach ( $users as $user ) {

			// If the user has the role and no other roles, set their role to the default.
			if ( $user->has_cap( $role ) && 1 >= count( $user->roles ) )
				$user->set_role( $default_role );

			// Else, remove the role.
			else if ( $user->has_cap( $role ) )
				$user->remove_role( $role );
		}
	}

	// Remove the role.
	remove_role( $role );

	// Remove the role from the role factory.
	members_unregister_role( $role );
}