Created
August 12, 2015 01:57
-
-
Save tannerm/1f096716697a8e6f1e87 to your computer and use it in GitHub Desktop.
Companion function for Conditional Profile Field Groups plugin to remove invalid group meta when a user's role changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function remove_prev_role_meta( $user_id = null) { | |
// Define the user we are working on | |
if ( ! $user_id ) { | |
$user_id = get_current_user_id(); | |
} | |
// Set valid groups | |
$valid_groups = bp_xprofile_get_groups( array( 'user_id' => $user_id ) ); | |
$valid_group_ids = wp_list_pluck( $valid_groups, 'id' ); | |
// remove conditional profile groups filter | |
remove_filter( 'bp_xprofile_get_groups', array( CFG_Setup::get_instance(), 'filter_org_groups' ) ); | |
// get all groups for this user that have field content that are not part of the valid list | |
$invalid_groups = bp_xprofile_get_groups( array( | |
'user_id' => $user_id, | |
'hide_empty_groups' => true, | |
'hide_empty_fields' => true, | |
'fetch_fields' => true, | |
'fetch_field_data' => true, | |
'fetch_visibility_level' => false, | |
'exclude_groups' => $valid_group_ids, | |
) ); | |
// re-hook up the conditional groups filter | |
add_filter( 'bp_xprofile_get_groups', array( CFG_Setup::get_instance(), 'filter_org_groups' ) ); | |
// if we have nothing, exit | |
if ( empty( $invalid_groups ) ) { | |
return; | |
} | |
// loop through the invalid groups. If usermeta is found, delete it. | |
foreach( $invalid_groups as $group ) { | |
if ( empty( $group->fields ) ) { | |
continue; | |
} | |
foreach ( $group->fields as $field ) { | |
if ( empty( $field->id ) ) { | |
continue; | |
} | |
xprofile_delete_field_data( $field->id, $user_id ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment