Skip to content

Instantly share code, notes, and snippets.

@andrewlimaza
Last active May 11, 2021 06:52
Show Gist options
  • Save andrewlimaza/1181f3d729294df3d15638b29a3a246d to your computer and use it in GitHub Desktop.
Save andrewlimaza/1181f3d729294df3d15638b29a3a246d to your computer and use it in GitHub Desktop.
Bulk Update Roles For Members (via Admin Script)
<?php
/**
* Bulk update user's based off their level via admin page.
* Add 'updateroles' to the URL with the value of the level ID you want to update user's for.
* This will only affect non-admins with an active membership level. Be sure to setup your level role settings per level before running this script.
*/
function bulk_update_roles_for_member_levels() {
if ( ! empty( $_REQUEST[ 'updateroles' ] ) && current_user_can( 'manage_options' )) {
global $wpdb;
$level_id = intval( $_REQUEST['updateroles'] );
$SQL = "SELECT user_id FROM $wpdb->pmpro_memberships_users WHERE status = 'active' AND membership_id = $level_id";
$results = $wpdb->get_results( $SQL, ARRAY_A );
if ( empty( $results ) ) {
echo "no members found for level ID (" . $level_id . ")";
exit;
}
$role = new PMPro_Roles();
foreach( $results as $users ) {
$user_id = $users['user_id'];
$user = new WP_User( $user_id );
$ignored_roles = array( 'administrator', 'editor' );
if ( array_intersect( $ignored_roles, $user->roles ) ) {
continue;
}
// If the user exists only.
if ( empty( $user->ID ) ) {
continue;
}
$role_changes = $role->user_change_level( $level_id, $user_id );
}
echo 'Script Finished';
exit;
}
}
add_action( 'init', 'bulk_update_roles_for_member_levels' );
@laurenhagan0306
Copy link

This recipe is included in the blog post on "How to Bulk Update User Roles to a Custom Role for Their Membership Level" at Paid Memberships Pro here: https://www.paidmembershipspro.com/how-to-bulk-update-user-roles-to-a-custom-role-for-their-membership-level/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment