Skip to content

Instantly share code, notes, and snippets.

@ipokkel
Created November 8, 2023 07:28
Show Gist options
  • Save ipokkel/867fb8103f7e789ae089e55cbc93a9dc to your computer and use it in GitHub Desktop.
Save ipokkel/867fb8103f7e789ae089e55cbc93a9dc to your computer and use it in GitHub Desktop.
<?php
/**
* Toggle user field readonly based on user meta value or user capabilities.
* This should allow members to fill in a field at checkout but set to readonly
* on their profile edit page if they are not an admin or do not have a value.
*
* This assumes a field's readonly property is set to true.
*
* 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_toggle_user_field_readonly() {
global $pmpro_user_fields, $current_user;
$readonly_fields = array( 'example_text' );
// Don't break if PMPro is out of date or not loaded.
if ( ! function_exists( 'pmpro_add_user_field' ) || empty( $pmpro_user_fields ) ) {
return;
}
foreach ( $pmpro_user_fields as $field_group => $fields ) {
foreach ( $fields as $field ) {
if ( in_array( $field->name, $readonly_fields ) ) {
// skip field if readonly is already false.
if ( ! $field->readonly ) {
continue;
}
// Remove readonly if user does not have a value for the field or is an admin.
if ( ! is_user_logged_in() || empty( get_user_meta( $current_user->ID, $field->meta_key, true ) ) || current_user_can( 'manage_options' ) || current_user_can( 'pmpro_membership_manager' ) ) {
$field->readonly = false;
}
}
}
}
}
add_action( 'init', 'my_pmpro_toggle_user_field_readonly' );
@ipokkel
Copy link
Author

ipokkel commented Nov 8, 2023

For setting default user fields, e.g. email address, to readonly see https://gist.github.com/ipokkel/9ea0a858661632d7f13c85b63299e846

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