Skip to content

Instantly share code, notes, and snippets.

@dparker1005
Last active March 31, 2023 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dparker1005/aef07e835f7a854a5d0d59d4cdabd706 to your computer and use it in GitHub Desktop.
Save dparker1005/aef07e835f7a854a5d0d59d4cdabd706 to your computer and use it in GitHub Desktop.
On login, loop through all user fields and check if any are taxonomy fields. If so, check the user's meta value for that field. If the taxonomy option label is stored, change it to the ID.
<?php
// Copy from below here...
/**
* On login, loop through all user fields and check if any are taxonomy fields.
* If so, check the user's meta value for that field. If the taxonomy option label
* is stored, change it to the ID.
*
* Upgrade script to go along with this bug fix PR: https://github.com/strangerstudios/paid-memberships-pro/pull/2423
*
* You can add this recipe to your site by creating a custom plugin
* or using the Code Snippets plugin available for free in the WordPress repository.
* Read this companion article for step-by-step directions on either method.
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
function my_pmpro_fix_taxonomy_user_field_data( $user_login, $user ) {
// Get all user fields.
global $pmpro_user_fields;
if ( empty( $pmpro_user_fields ) ) {
return;
}
// Loop through all user field groups.
foreach ( $pmpro_user_fields as $field_group ) {
// Loop through all fields in this group.
foreach ( $field_group as $field ) {
// Check if this is a taxonomy field.
if ( property_exists( $field, 'taxonomy' ) && ! empty( $field->taxonomy ) ) {
// Get the user's meta value for this field.
$meta_value = get_user_meta( $user->ID, $field->name, true );
// Check if $meta_value is an array.
if ( is_array( $meta_value ) ) {
// Loop through all values in the array.
foreach ( $meta_value as $key => $value ) {
// Check if the value is a taxonomy option label.
$term = get_term_by( 'name', $value, $field->taxonomy );
if ( $term ) {
// Change the value to the taxonomy option ID.
$meta_value[ $key ] = $term->term_id;
}
}
} else {
// Check if the value is a taxonomy option label.
$term = get_term_by( 'name', $meta_value, $field->taxonomy );
if ( $term ) {
// Change the value to the taxonomy option ID.
$meta_value = $term->term_id;
}
}
// Update the user's meta value for this field.
update_user_meta( $user->ID, $field->name, $meta_value );
}
}
}
}
add_action( 'wp_login', 'my_pmpro_fix_taxonomy_user_field_data', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment